Java is a simple
programming language. Java makes it straightforward to write, compile, and
debug programming. It helps to make reusable code and modular programs. Java is
a universal programming language built for developers to write at runtime where
Java code is compiled, it can operate on all platforms supporting Java. Java
applications are compiled into bytecodes that can run on any Java Virtual
Machine. The syntax of Java is similar to c/c++.
This blog will cover collections in Java and how to implement
them.
Collections in Java
“ Java Collection Framework
“ Hierarchy Collection Framework
“ Collection interface
“ Iterator interface
A collection in Java is a framework that
provides an architecture for storing and manipulating a group of objects.
Java collections can
perform all the operations you perform on data, such as searching, sorting,
inserting, manipulating, and deleting.
A Java Collection
means a single unit of objects. The Java Collection framework furnishes
multiple interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
The collection
framework is a suitable architecture for defining and manipulating collections.
All collection frames include the following:
Interfaces:
These are notional data types that describe collections. Interfaces allow
groups to be manipulated independently of the details of their representation.
Implementations, i.e.,
classes ? These are specific
implementations of collection interfaces. Basically, these are reusable data
structures.
Algorithms:
These methods perform valuable computations on objects that implement
collection interfaces, such as searching and sorting. Algorithms are declared
polymorphic: the same technique can be applied to various implementations of
the relevant collection interface.
Now you are probably
wondering what a framework is. So let’s understand what a framework is.
What is a framework?
A framework is a pack
of classes and interfaces that deliver a finished architecture. There is no
demand to specify a framework to implement a new function or class. However,
optimal object-oriented design always includes a framework with a collection of
classes so that all classes perform the same task.
Why do we need a different collection framework?
Before the Collection
Framework (or JDK 1.2), the standard methods for grouping Java objects (or
collections) were Arrays Vectors or Hashtables. All these collections had no
standard interface. Therefore, even though the primary goal of all groups is
the same, the enactment of all these collections was determined independently
and had no correlation. And it’s also challenging for users to remember all the
different methods, syntax, and constructors in each collection class.
Advantages of the Collection Framework:
Since the scarcity of
a collection framework has offered rise to the above set of disadvantages, here
are the advantages of the collection framework.
Consistent API: An API has a core set of interfaces like Collection,
Set, List, or Map, all classes (ArrayList, LinkedList, Vector, etc.) that
implement these interfaces have some standard set of methods.
Reduces programming effort: The programmer does not have to worry about the
collection’s design. But instead, he can focus on making the best use of it in
his program. Therefore, the fundamental concept of object-oriented programming
(i.e., abstraction) was successfully implemented.
Increases program speed and quality: Increases execution by providing
high-performance implementations of functional data structures and algorithms
since the programmer does not have to think about the best implementation of a
particular data structure. He can easily use the best performance to
drastically increase the performance of his algorithm/program.
Collection interface methods
This interface
contains various methods that can be used directly by all collections
implementing this interface. They are:
add(Object): This mode is used to add an object to the collection.
addAll(Collection c): This process adds all the elements in the given
collection to this collection.
clear(): This approach removes all elements from this collection.
contains(Object o): This approach returns true if the collection contains
the specified element.
containsAll(Collection c): This procedure returns true if the collection contains
all the elements in the given collection.
equals(Object o): This technique compares the specified object with this
collection for equality.
hashCode()
: This approach returns the hash code value for this collection.
isEmpty()
: This process returns true if this collection contains no elements.
iterator()
: This approach returns an iterator over the elements in this collection.
max() :
This procedure returns the maximum value present in the collection.
parallelStream() : This method returns a parallel stream with this
collection as its source.
remove(Object o) : This method removes the given entity from the
collection. If there are same values, then this method will remove the first
occurrence of the thing.
removeAll(Collection c) : This method removes all objects listed in the given
collection from the collection.
removeIf(Predicate filter) : This method removes all elements of this collection
that satisfy the given predicate.
keepAll(Collection c) : This method is used to keep only the elements in this
collection that are contained in the specified collection.
size()
: This approach returns the number of elements in the collection.
spliterator() : This method is used to create a Spliterator over the
elements in this collection.
stream()
: This approach returns a sequential Stream with this collection as its origin.
toArray()
: This process returns an array containing all elements in this collection.
Now let’s discuss a collection of java interview questions.
1. How would you
convert ArrayList to Array and Array to ArrayList?
An array can be
converted to an ArrayList using the asList() was provided by the Array class.
It is a static approach that accepts list objects as a parameter.
Syntax:
“`
Arrays.asList(item)
“`
An ArrayList can be
transformed to an Array using the toArray() method of the ArrayList class.
Syntax:
“`
List_object.toArray(new
String[List_object.size()])
“`
2. How do you change
the list?
An ArrayList can be
reversed using the reverse() method of the Collections class.
Syntax:
“`
public static void
reverse(Collection c)
“`
For Example:
“`
public class ReversingArrayList {
public static void main(String[] args) {
List myList = new ArrayList();
myList.add(“AWS”);
myList.add(“Java”);
myList.add(“Python”);
myList .add(“Blockchain”);
System.out.println(“Before Reversing”);
System.out.println(myList.toString());
Collections.reverse(myList);
System.out.println(“After Reversing”);
System.out.println(myList);
}
}
3. Explain equals()
with an example
Equals() check
whether the number object is equal to the object passed as an argument or not.
The syntax of the
equals() method is:
“`
public boolean
equals(Object o)
“`
This method takes two
parameters 1) an arbitrary object and 2) a return value. Returns true if the
argument passed is not null and is an object of a similar type with the same
numeric value.
Example:
Import java.lang.Integer;
public class Test {
public static void main(String args[]) {
Integer p = 5;
Integer q = 20;
Integer r =5;
Short s = 5;
System.out.println(p.equals(q));
System.out.println(p.equals(r));
System.out.println(p.equals(s));
}
}
4. List the
advantages of a generic collection
The benefits of using
a generic collection are:
” If programmers use generic classes, they do
not require type casting.
” It is type-safe and can be checked at compile
time.
” It provides code stability by detecting errors
at compile time.
5. Define
BlockingQueue
BlockingQueue is an
interface that utilizes in Java that can extend a queue. It delivers
concurrency in various queue operations like fetch, insert, delete, etc.
The queue waits until
it is empty when loading any elements. BlockingQueue should not contain null
elements. The execution of this queue is thread-safe.
The BlockingQueue syntax
is:
“`
public interface
BlockingQueue extends Queue
“`
Summary
The Java collection framework provides the
programmer access to prepackaged data structures and algorithms for
manipulating them.
A collection is an
object that can contain references to other things. Collection interfaces
declare the functions that can be executed on each type of collection.
Collection framework
classes and interfaces are in the java.util package.