Java Collections Interview Questions and Answers
Java Collections Interview Questions and Answers
Java Collection Framework was introduced in JDK 1.2 which contains all the collection classes and
interfaces. Java Collection is a framework that provides a mechanism to store and manipulate the
collection of objects. It allows developers to access prepackaged data structures and algorithms for
manipulating data.
The term collection refers to a group of objects represented as one unit. Classes in the Java
collection class hierarchy are divided into two “root” interfaces: Collection (java.util.Collection) and
Map (java.util.Map). Terms that you will encounter while learning about the collection in Java:
Collection Framework: Java’s Collection Framework defines classes and interfaces for
representing groups of objects as a single entity. C++ developers can compare the Collection
framework with STL (Standard Template Library) and Container Framework with the
Collection Framework if they come from a C++ background.
Collection Interface: A class’s interface specifies what it should do, not how. In other words,
it is the blueprint for the class. This interface provides the most common methods for all
collection objects that are part of the Collection Framework. Alternatively, it represents the
individual object as a whole.
Frameworks are sets of classes and interfaces that provide a ready-made architecture. It is not
necessary to define a framework in order to implement new features or classes. As a result, an
optimal object-oriented design includes a framework containing a collection of classes that all
perform similar tasks. The framework can be used in a variety of ways, such as by calling its methods,
extending it, and supplying “callbacks”, listeners, and other implementations. Some of the popular
frameworks in java are:
Spring
Hibernate
Struts
Arrays are a collection of similar-typed variables with a common name in Java. There are some
differences between arrays in Java and C/C++. On the other hand, Collections are groups of individual
objects that form a single entity known as the collection of objects.
Arrays Collection
Arrays are fixed in size that is once we create an The collection is growable in nature and is
array we can not increase or decrease based on based on our requirements. We can increase
our requirements. or decrease of size.
With respect to memory, Arrays are not With respect to memory, collections are
recommended for use. recommended for use.
With respect to performance, Arrays are With respect to performance, collections are
recommended for use. not recommended for use.
Arrays can hold only homogeneous data types Collection can hold both homogeneous and
elements. heterogeneous elements.
The collection is known as the root of the collection hierarchy. Collections represent groups of
objects known as elements. The java platform does not provide any direct implementation of this
interface but the Collection interface is being implemented by List and Set classes.
Collection interface
List interface
Set interface
Queue interface
Dequeue interface
Map interface
All classes and interfaces required by the collection framework are contained in the utility package
(java. util). Collection frameworks have an interface called an iterable interface, which allows the
iterator to iterate over all collections. In addition to this interface, the main collection interface acts
as a root for the collection framework. All the collections extend this collection interface thereby
extending the properties of the iterator and the methods of this interface. The following figure
illustrates the hierarchy of the collection framework.
6. What are the advantages of the collection Framework?
Advantages of the Collection Framework: Since the lack of a collection framework gave rise to the
above set of disadvantages, the following are the advantages of the collection framework.
Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the
classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces
have some common set of methods.
Reduces programming effort: A programmer doesn’t have to worry about the design of the
Collection but rather he can focus on its best use in his program. Therefore, the basic
concept of Object-oriented programming (i.e.) abstraction has been successfully
implemented.
ArrayList is a part of the Java collection framework and it is a class of java.util package. It provides us
with dynamic arrays in Java. The main advantages of ArrayList are, if we declare an array then it’s
needed to mention the size but in ArrayList, it is not needed to mention the size of ArrayList if you
want to mention the size then you can do it.
It is used to represent a group of individual It defines several utility methods that are
objects as a single unit. used to operate on collection.
ArrayList LinkedList
This class uses a dynamic array to store the This class uses a doubly linked list to store the
elements in it. With the introduction of elements in it. Similar to the ArrayList, this class
generics, this class supports the storage of all also supports the storage of all types of
types of objects. objects.
Manipulating ArrayList takes more time due to Manipulating LinkedList takes less time
the internal implementation. Whenever we compared to ArrayList because, in a doubly-
ArrayList LinkedList
This class works better when the application This class works better when the application
demands storing the data and accessing it. demands manipulation of the stored data.
Java’s Collection framework uses iterators to retrieve elements one by one. This iterator is universal
since it can be used with any type of Collection object. Using Iterator, we can perform both reading
and removing operations. This is an improved version of Enumeration with the addition of removing
elements.
Syntax:
Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to “c”.
A major difference between iterator and enumeration is that iterators have a remove() method while
enumerations do not. Thus, using Iterator we can manipulate objects by adding and removing them
from collections. Since enumeration can only traverse objects and fetch them, it behaves like a read-
only interface.
A major difference between a List and a Set is that a List can contain duplicate elements while a set
contains only unique elements. The list is Ordered and maintains the order of the object to which
they are added. The set is unordered.
List Set
The list allows duplicate elements The set doesn’t allow duplicate elements.
Elements by their position can be accessed. Position access to elements is not allowed.
Multiple null elements can be stored. Null elements can store only once.
13. What are the best practices for Java Collections Framework?
Following are some of the best practices while using Java Collections:
Whenever possible, use Generics to ensure type safety and avoid ClassCastExceptions.
Choosing the appropriate type of collection based on the need. For example, if the size is
fixed, we might want to use an Array over an ArrayList. When iterating over the Map, we
should use LinkedHashMap. Set is the best way to avoid duplicates.
In order to increase the readability of the code, we should use isEmpty() instead of finding
the size of the collection and comparing it to zero.
Rather than writing your own implementation, use the Collections utility class to get read-
only, Synchronized, or empty collections instead. It enhances code reuse while resulting in
greater stability.
PriorityQueues are used to process objects according to their priority. Queues follow the First-In-
First-Out algorithm, but sometimes the elements of the queue need to be processed according to
their priority, which is where PriorityQueue comes into play. Priority queues are based on priority
heaps.
The elements of the priority queue are ordered according to the natural ordering, or by a
Comparator provided at queue construction time, depending on which constructor is used.
Priority Queues in Java
Declaration:
15. What is the difference between List, set, and map in java?
The list interface allows The set does not allow The map does not allow duplicate
duplicate elements duplicate elements. elements
The list maintains The set does not maintain The map also does not maintain any
insertion order. any insertion order. insertion order.
We can add any number But in the set almost only The map allows a single null key at
of null values. one null value. most and any number of null values.
In stacks, insertion, and deletions take In queues, insertion occurs at the rear of the list
place only from the top. and deletion takes place from the front of the list.
Insert operation is called push operation. Insert operation is called enqueue operation.
Delete operation is called pop operation. Delete operation is called dequeue operation.
The BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility
classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc. The
BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either
BlockingQueue is full or empty.
A thread trying to enqueue an element in a full queue is blocked until some other thread makes
space in the queue, either by dequeuing one or more elements or clearing the queue completely.
Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an
item. BlockingQueue does not accept a null value. If we try to enqueue the null item, then it throws
NullPointerException.
Usage of BlockingQueue
Blocking Queue in Java
Declaration:
hashCode() method returns the hashcode value as an Integer. It is defined in the Java Object class
which computes the hash values of given input objects. Hashcode value is mostly used in hashing-
based collections like HashMap, HashSet, HashTable….etc. This method must be overridden in every
class which overrides the equals() method.
Syntax :
19. Distinguish between ArrayList and Vector in the Java Collection Framework.
In collection interviews, this question is frequently asked; however, Vector is synchronized whereas
ArrayList is not. ArrayList is faster than Vector. ArrayList’s Array size is increased by 50% when
needed, while Vector’s capacity is doubled whenever it is needed.
Array List vs Vector in java
ArrayList Vector
The size of ArrayList is incremented up to 50% The size of Vector is incremented up to 100%
of the current array size if the number of of the current array size if the number of
elements exceeds its capacity. elements exceeds its capacity.
The iterator interface is used to traverse the An iterator interface or Enumeration can be
elements used to traverse the vector.
Iterator ListIterator
Helps to traverse Map, List, and Set. Can only traverse List and not the other two.
Iterator ListIterator
Cannot modify or replace elements We can modify or replace elements with the help of set(E
present in the Collection e)
Iterator: It is a universal iterator as we can apply it to any Collection object. By using an Iterator, we
can perform both read and remove operations.
Syntax:
Enumeration: Enumeration (or enum) is a user-defined data type. It is mainly used to assign names
to integral constants, the names make a program easy to read and maintain.
Syntax:
Iterator Enumeration
The iterator can do modifications (e.g using The enumeration interface acts as a read-only
the remove() method which removes the interface, one can not do any modifications to
Iterator Enumeration
element from the Collection during the Collection while traversing the elements of
traversal). the Collection.
HashMap is similar to HashTable, but it is unsynchronized. It allows us to store the null keys as well,
but there should be only one null key object and there can be any number of null values. This class
makes no guarantees as to the order of the map. To use this class and its methods, you need to
import java.util. HashMap package or its superclass.
HashMap in Java
Syntax:
For Example, the HashSet class implements the Set interface which is a subinterface of the Collection
interface. If a collection implementation doesn’t implement a particular operation, it should define
the corresponding method to throw UnsupportedOperationException.
In Java, the List interface allows the user to store an ordered collection of objects. The list is the child
interface of Collection. In Collection, a list is an ordered collection of objects which can have
duplicate values. Since List preserves the insertion order, it allows positional access and insertion,
which also allows duplicate values.
Syntax:
This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the
subclasses implement the list, we can instantiate a list object with any of these classes.
Example:
ArrayList
LinkedList
Vector
Stack
25. Write a program to convert a given array into a collection with the asList() method.
To convert array-based data into Collection based we can use java.util.Arrays class. This class
provides a static method asList(T… a) that converts the array into a Collection.
Java
import java.util.*;
// array input
"Abhishek", "Shivansh" };
+ Arrays.toString(students));
Output
HashSet HashMap
HashSet implements the Set interface HashMap implements the Map interface
Add() method is used for the insertion The put () method is used for insertion.
Objects that you insert in HashSet are not guaranteed to be inserted HashTable does not
in the same order. Objects are inserted based on their hash code. maintain insertion
LinkedHashSet can be used to maintain order. order.
HashTable is
HashSet is not Synchronized but it can be synchronized externally.
Synchronized.
28. What is the default size of the load factor in the hashing-based collection?
As the Load Factor increases, the capacity increases so that the operational complexity of the
HashMap remains O(1) if the ratio of the current element to the initial capacity crosses the
threshold. The meaning of operational complexity of O(1) means the retrieval and insertion
operations take constant time. The default load factor size is 0.75. The default capacity is calculated
by multiplying the initial capacity by the load factor.
Java provides two interfaces to sort objects using data members of the class:
Comparable
Comparator
Comparable Comparator
The Comparable interface provides a single The Comparator interface provides multiple
sorting sequence. sorting sequences.
The actual class is modified by a comparable The actual class is not modified by the
interface Comparator interface.
compareTo() method is used to sort elements. compare() method is used to sort elements.
Comparable Comparator
Iterators in Java are used to iterate over the Collection objects. Fail-Fast iterators immediately
throw ConcurrentModificationException if there is a structural modification of the collection.
Structural modification means adding, or removing any element from a collection while a thread is
iterating over that collection. Iterator on ArrayList and HashMap classes are some examples of fail-
fast Iterator.
Fail-Fast Fail-Safe
ConcurrentModificationException is
thrown while modifying the object during No Exception is thrown
the iteration process.
Fail-Fast needs less memory during the Fail-Safe iterator requires more memory during the
process. process.
A clone Object is not created during the A clone Object or a Copy is created during the
iteration process. iteration process.
Fail-Fast does not allow modification Fail-Safe allows modification during the process of
during the process of iteration. iteration.
Examples: Examples:
31. Write a program to iterate the list using the lambda expression.
Syntax:
list_name.forEach(variable->{//block of code})
// java.util method
import java.util.*;
// Class
class GFG {
// Creating an ArrayList
// Custom inputs
l.add("Geeks");
l.add("for");
l.add("Geeks");
Output
Geeks
for
Geeks
The IdentityHashMap implements the Map interface using Hashtable, comparing keys (and values)
using reference equality instead of object equality. This class implements the Map interface, but it
intentionally breaks Map’s general contract, which demands that objects are compared using the
equals() method. This class is used when the user allows objects to be compared using references. It
belongs to java.util package.
33. Write a program in Java to display the contents of a HashTable using enumeration.
The hashtable class implements a hash table, which maps keys to values. Any non-null object can be
used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects
used as keys must implement the hashCode method and the equals method. Below is the program to
display the contents of a HashTable using enumeration:
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
// Main class
// EnumerationOnKeys
hash.put(1, "Geeks");
hash.put(2, "for");
hash.put(3, "Geeks");
// to read elements
Enumeration e = hash.elements();
// using enumeration
while (e.hasMoreElements()) {
// Printing the current element
System.out.println(e.nextElement());
Output
Geeks
for
Geeks
34. Write a program in java to get the collection view of the values present in a HashMap.
Java’s HashMap class has the java.util.HashMap.values() method for creating collections out of
HashMap values. It basically returns a Collection view of HashMap values.
import java.util.*;
hash_map.put(0, "Welcome");
hash_map.put(1, "to");
hash_map.put(2, "Geeks");
hash_map.put(3, "4");
hash_map.put(4, "Geeks");
}}
Output
For more information, refer to the article – HashMap values() Method in Java
35. Write a program to join two ArrayList into one single ArrayList.
import java.util.*;
list_1.add("Geeks");
list_1.add("For");
list_1.add("ForGeeks");
list_2.add("GeeksForGeeks");
// arraylist
list_1.addAll(list_2);
}
Output
For more information, refer to the article – Join two ArrayLists in Java
import java.io.*;
import java.util.*;
class GFG {
list.add("Eat");
list.add("Coffee");
list.add("Code");
list.add("Sleep");
list.add("Repeat");
list = Collections.synchronizedList(list);
// non-deterministic behavior
synchronized (list)
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
Output
Eat
Coffee
Code
Sleep
Repeat
The properties class is a subclass of Hashtable. The properties class stores a list of values whose key
is a string and whose value is also a string. Properties can define other properties class lists, but the
default is properties.
The Properties file is used to store and retrieve string data type for a list of values where the
key is a string and the value is also a string.
If the original properties list does not contain a certain key property, the default properties
list will be searched instead.
The properties class can be used to retrieve the properties of the system.
38. What will happen if you use HashMap in a multithreaded Java application?
In a multi-threaded environment, if multiple threads alter the map structurally, such as adding,
removing, or modifying mappings, the internal data structure of HashMap may become corrupted
and there may be some missing links, incorrect entries, and the map itself may become completely
useless. Thus, you should not use HashMap in a concurrent application; instead, use
ConcurrentHashMap or Hashtable which is thread-safe. The ConcurrentHashMap includes all the
Hashtable’s methods as well as full concurrency of retrievals and updates.
39. What will happen if two different keys of HashMap return the same hashcode()?
When two different keys of HashMap return the same hash code, they will end up in the same
bucket; therefore, collisions will occur. n case of collision, i.e. index of two or more nodes is the
same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third
by the second, and so on.
For more information, refer to the article – Internal Working of HashMap in Java
WeakHashMap implements the Map interface. Unlike HashMap, WeakHashMap allows garbage
collection even if the object specified as the key doesn’t contain any references despite being
associated with WeakHashMap. In other words, Garbage Collector is better than WeakHashMap.
Syntax:
Creating a Read-Only Collection involves restricting the object to only fetching the data and not
adding or removing data. Java has different methods for different Collection types like
unmodifiableCollection(), unmodifiableMap(), ununmodifiableSet(), etc. java.util.The collections class
defines all methods. The unmodifiableCollection() method creates a Read-Only collection. It requires
a reference to the Collection class. If we have an object of Set Interface, we can
use ununmodifiableSet() to make Read-Only.
For more information, refer to the article – How to Make a Collection Read-Only in Java?
PriorityQueue TreeSet
For more information, refer to the article – Difference Between PriorityQueue and TreeSet
Diamond operators are used for simplifying the use of generics when creating objects while avoiding
unchecked warnings in a program. When the Diamond operator was introduced in Java 7, we can
create the object without mentioning the generic type on the right side of the expression as shown
below.
Syntax:
TreeMap stores the key-value pairs, but TreeMap sorts the keys ascending rather than descending
like HashMap. Depending on which constructor is used, TreeMap will be sorted either based on its
keys, or by a Comparator. In TreeMap, the elements are sorted based on a Red-Black tree. A red-
black tree is a self-balancing binary search tree where each node has an extra bit, and that bit is
often interpreted as the color (red or black). These colors are used to ensure that the tree remains
balanced during insertions and deletions.
Structure of a Node in Java
For more information, refer to the article – Internal Working of TreeMap in Java
The HashMap class provides Java’s Map interface by storing data in (Key, Value) pairs and accessing
them by an index of another type. To use this class it is necessary to
import java.util.HashMap package or its superclass.
There are numerous ways to iterate over HashMap of which 5 are listed below:
For more information, refer to the article – How to Iterate HashMap in Java
JDK 1.5 introduced an enhanced version of ArrayList called CopyOnWriteArrayList, where all
modifications (add, set, remove, etc) are implemented by a new copy. It can be found in
java.util.concurrent. It is a data structure created to be used in a concurrent environment. In a
Thread-based environment, the CopyOnWriteArrayList is intended for frequent reading and
infrequent updating. CopyOnWriteArrayList is a thread-safe version of ArrayList.
EnumMap is an implementation of the Map interface specific to enumeration types. EnumMap class
is a member of the Java Collections Framework & is not synchronized. It extends AbstractMap and
implements the Map interface in java. EnumMap belongs to java.util package.
Syntax:
// K must extend Enum, which enforces the requirement that the keys must be of the specified enum
type.
Parameters:
HashMap works on the principle of Hashing. HashMap contains an array of Node and Node can
represent a class having the following objects:
int hash
K key
V value
Node next
Hashing
Buckets
For more information, refer to the article – Internal Working of HashMap in Java
fail-fast iterators immediately throw concurrent modification exceptions if any thread from outside
attempts to modify the collection on which they are iterating. The fail-fast feature ensures that the
iterator fails immediately if it detects that any modification of the collection will lead to anomalous
behavior in the future.
Fail fast feature ensures that if iterator feels that modification of collection would result in
anomalous behaviour at any point of time in future, it fails immediately.
Example:
// Java code to demonstrate remove
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
Iterator<Integer> it = arr.iterator();
while (it.hasNext()) {
if (it.next() == 2) {
it.remove();
System.out.println(arr);
it = arr.iterator();
while (it.hasNext()) {
if (it.next() == 3) {
arr.remove(3);
}
}
Output:
[1, 3, 4, 5]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at FailFastExample.main(FailFastExample.java:28)