This Tutorial Includes a list of the Most Frequently Asked Java Collections Interview Questions along with Answers and Examples for you:
The core API of Java is the Java Collections Framework. It supports the fundamental concept of this programming language. If you want to be a Java developer, you should be well aware of these core concepts.
The area of Java collections is extremely wide and many questions can be asked in an interview. Here we have collected a list of as many relevant questions that you might be asked in your interview.
=> Check Here To See A-Z Of Java Training Tutorials Here
Table of Contents:
Java Collections Interview Questions
Q #1) Explain the Java Collections Framework.
Answer: The Java Collections Framework is an architecture that helps in managing and storing a group of objects. With it, the developers can access prepackaged data structures and manipulate data with the use of algorithms as well.
Java collection includes the interface, and classes, that support operations like searching, deleting, insertion, sorting, etc. Along with interface and classes, Java Collections include algorithms as well that helps in manipulations.
Q #2) What are the benefits of Java Collections?
Answer:
The benefits of Java Collections are:
- Instead of implementing our collection classes, it uses the core collection classes, thereby reducing the effort required for its development.
- It uses the collection framework classes that are well tested. Hence, its code quality is enhanced.
- It reduces the effort in code maintenance.
- Java Collection Framework is interoperable and reusable.
Q #3) What do you know about the Hierarchy of Collections in Java?
Answer:
[image source]
Q #4) Tell us about the Java Collection’s basic interfaces.
Answer:
Enlisted below are the basic interfaces of the Java Collection Framework.
Collection: It is the base of the Collection hierarchy and represents its elements. However, Java doesn’t provide any direct application of Collection. Also, most of the Java collections come from this interface.
Set: It cannot hold duplicate elements as it models the abstraction of the mathematical set. As the name suggests, it represents sets, for example, a deck of cards.
List: It can hold duplicate elements and is an ordered collection. You can use its index to access any element in it. The list is like an arrangement, an array, with a dynamic length.
These are a few interfaces of Java Collection. However, there are a few more interfaces as well as shown below.
- Queue
- Dequeue
- Iterator
- Iterable
- SortedSet
- ListIterator.
Q #5) Why Serializable and Cloneable Interfaces are not extended by the Collection Interface?
Answer: The task of the Collection Interface is to specify a group of objects called elements. The implementation of the Collections decides how the elements will be maintained. For example, the List implementations allow duplicate elements but Set implementations don’t.
Many implementations have a method for public cloning. But it isn’t practical to include it in all Collection implementations as the Collection is abstract and implementation is all that matters.
The meaning and the ramifications of both serialization and cloning makes sense while working with the substantive implementations. Hence, it is up to the actual implementation to decide if it can be serialized or cloned and how.
Learn more =>> Marker Interface In Java: Serializable And Cloneable
That’s why inducting serialization and cloning in every implementation isn’t very flexible and is restrictive.
Q #6) What do you understand by Iterator in the Java Collection Framework?
Answer: In simples arrays, we can use loops to access each element. When a similar approach is needed to access elements in a collection, we go for iterators. Iterator is a construct used to access elements of Collection objects.
In Java, Iterators are the objects that implement the “Iterator” interface of Collection Framework. This interface is a part of the java.util package.
Some of the characteristics of Iterators are:
- Iterators are used to traverse the Collection objects.
- Iterators are known as “Universal Java Cursor” as we can use the same Iterator for all the collections.
- Iterators provide “Read” and “Remove” operations apart from traversing the collections.
- As they are universal and work with all the collections, Iterators are easier to implement.
List Java Collection Questions
Q #7) Are you aware of the uses of the List Interface?
[image source]
Answer: The purpose of the List Interface is to maintain the order of the insertion. It also allows the storage of duplicate values.
It helps in the smooth manipulation of the elements depending on its index with the various methods it contains. ArrayList, Vector, Stack, and LinkedList are the various classes that implement the List Interface.
Also Read => Top Java Architect Interview Questions
Q #8) What do you understand about ArrayList in Java?
Answer: The implementation of the List Interface is ArrayList. It dynamically adds or removes elements from the list and it also provides insertion of elements along with the positional access. ArrayList permits duplicate values and its size can dynamically increase if the number of the elements exceeds the initial size.
Q #9) How will you convert a string array to an ArrayList?
Answer: This is a beginner’s level programming question that an interviewer asks to check your grasp of Collection utility.classes. Collection and Arrays are the two utility classes of the Collection Framework that interviewers are often interested in.
Collections offer certain static functions for performing specific tasks on collection types. While Array has utility functions that it performs on array types.
//String array String[] num_words = {"one", "two", "three", "four", "five"}; //Use java.util.Arrays class to convert to list List wordList = Arrays.asList(num_words);
Note that apart from String type, you can also use other type Arrays to convert to ArrayList.
For example,
//Integer array Integer[] numArray = {10,20,30,40}; //Convert to list using Arrays class asList method List num_List = Arrays.asList(numArray);
Q #10) Convert Array to ArrayList and ArrayList to Array.
Answer: To convert ArrayList to Array, the toArray() method is used- List_object.toArray(new String[List_object.size()])
While the asList() method is used for converting Array to ArrayList- Arrays.asList(item). The asList() is a static method where List objects are the parameters.
Q #11) What is a LinkedList and how many types of it are supported in Java?
[image source]
Answer: LinkedList is a data structure with a sequence of links where every link is connected to the next link.
Two types of LinkedList are used in Java for storing the elements:
- Singly LinkedList: Here, each node stores the data of the node along with a reference or the pointer to the next node.
- Doubly LinkedList: A doubly LinkedList comes with dual references, one reference to the next node, and another one for the previous node.
Q #12) What do you understand by BlockingQueue?
Answer: In a simple queue, we know that whenever the queue is full, we cannot insert any more items. In this case, the queue simply provides a message that the queue is full and exits. A similar case happens when the queue is empty and there is no element to be removed in the queue.
Instead of just exiting when insert/remove cannot be done, how about we wait till we can insert or remove the item?
This is answered by a variation of queue called “Blocking queue”. In blocking queue, blocking is activated during enqueue and dequeue operations whenever the queue is trying to enqueue full queue or dequeue an empty queue.
The blocking is shown in the following figure.
BlockingQueue
Thus, during enqueue operation, the blocking queue will wait till a space becomes available so that an item can be successfully inserted. Similarly, in the dequeue operation blocking queue will wait until an item become available for the operation.
Blocking queue implements ‘BlockingQueue’ interface that belongs to ‘java.util.concurrent’ package. We should remember that the BlockingQueue interface does not allow null value. If it encounters null, then it throws NullPointerException.
Q #13) What is a Priority Queue in Java?
Answer: A priority queue in Java is similar to stack or queue data structures. It is an abstract data type in Java and is implemented as a PriorityQueue class in java.util package. The priority queue has a special feature that each item in the Priority queue has a priority.
In a priority queue, an item with higher priority is the server before the item with lower priority.
All the items in the priority queue are ordered as per natural ordering. We can also order the elements according to custom order by providing a comparator at the time of creating a priority queue object.
Set Interface Interview Questions
Q #14) What is the use of Set Interface? Tell us about the classes implementing this Interface.
Answer: Set Interface is used in the set theory to shape the mathematical set. It is similar to the List interface and yet is a little different from it. Set Interface isn’t an ordered collection hence, there is no preserved ordering when you are removing or adding the elements.
Mainly, it doesn’t support duplicate elements thus each element in the Set Interface is unique.
It also allows meaningful comparisons of Set instances even when there are different implementations. Also, it puts in a more substantial contract on the actions of the operations of equals and hashCode. If two examples have the same elements, then they are equal.
For all these reasons, Set Interface doesn’t have element index-based operations like List. It only uses Collection Interface inherited methods. TreeSet, EnumSet, LinkedHashSet, and HashSet implements Set Interface.
Q #15) I want to add a null element to HashSet and TreeSet. Can I?
Answer: You can’t add any null element in TreeSet as it uses NavigableMap for element storage. But you can add just one to HashSet. SortedMap doesn’t allow null keys and NavigableMap is its subset.
That’s why you can’t add a null element to TreeSet, it will come up with the NullPointerException every time you try to do that.
Q #16) What do you know about LinkedHashSet?
Answer: LinkedHashSet is the subclass of HashSet and it enforces the Set Interface. As an ordered form of HashSet, it manages a doubly-linked List throughout all the elements it contains. It retains the order of insertion and just like its parent class, it only carries unique elements.
Q #17) Talk about the way HashSet stores elements.
Answer: HashMap stores the pairs of key-values but the keys should be unique. This feature of Map is used by HashSet to make sure every element is unique.
The Map declaration in HashSet appears as shown below:
private transient HashMap<E,Object>map; //This is added as value for each key private static final Object PRESENT = new Object();
The stored elements in HashSet are stored as a key in the Map and the object is presented as a value.
Q #18) Explain the EmptySet() method.
Answer: The Emptyset() method removes the null elements and returns the empty unchangeable set. This immutable set is serializable. The method declaration of the Emptyset() is- public static final <T> Set<T> emptySet().
Map Interface Interview Questions
Q #19) Tell us about the Map Interface.
Answer: Map Interface is designed for faster lookups and it stores the elements in the form of pairs of key-values. As every key is unique here, it connects or maps to a single value only. These pairs of key-values are called map entries.
In this interface, there are method signatures for retrieval, insertion, and removal of elements depending on the unique key. This makes it a perfect tool for mapping key-value associations, like a dictionary.
Q #20) The map doesn’t extend the Collection Interface. Why?
Answer: The collection Interface is the accumulation of objects and these objects are stored structurally with the mechanism of specified access. While the Map interface follows the structure of key-value pairs. The add method of the Collection Interface doesn’t support the put method of Map Interface.
That’s why Map doesn’t extend the Collection Interface but still, it is an important part of the Java Collection Framework.
Q #21) How does HashMap work in Java?
Answer: HashMap is a collection based on Map and its items consist of key-value pairs. A HashMap is typically denoted by <Key, Value>, or <K, V>. Each hashmap element can be accessed using its key.
A HashMap works on the principle of “Hashing”. In the hashing technique, a longer string is transformed into a smaller string by a ‘hash function’ which is nothing but an algorithm. The smaller string aids in faster searching and efficient indexing.
Q #22) Explain IdentityHashMap, WeakHashMap, And ConcurrentHashMap.
Answer:
IdentityHashMap is much like HashMap. The difference is that while comparing elements, IdentityHashMap uses reference equality. It is not a preferred Map Implementation and although it executes the Map Interface, it fails to comply with the general contract of the Map intentionally.
So, when comparing objects, this authorizes the use of the equals method. It is designed for usage in rare cases where one needs reference-equality semantics.
WeakHashMap Implementation stores only weak references to its keys. This allows the garbage collection of a key-value pair when there is no more reference of its keys outside the WeakHashMap.
It is primarily used with those key objects where the test for object identity is carried out by its equals methods using the == operator.
ConcurrentHashMap implements both ConcurrentMap and Serializable interfaces. It is the upgraded, enhanced version of HashMap as it doesn’t work well with the multithreaded environment. When compared to the HashMap, it has a higher performance rate.
Q #23) What is the quality of a good key for HashMap?
Answer: Understanding how HashMap works, it is easy to know that they depend mainly on equals and hashCode methods of key objects. So, a good key must provide the same hashCode over and over again irrespective of the times it is fetched.
In the same way, when compared with the equals method, the same keys must return true and different keys must return false. That’s why the best candidate for HashMap keys is said to be immutable classes.
Q #24) When can you use TreeMap?
[image source]
Answer: TreeMap, as a special form of HashMap, maintains the ordering of the keys by default ‘natural ordering’, as something that is missing in HashMap. You can use it for sorting objects with some key.
For example, if you want to implement and print a dictionary in alphabetical order, you can use TreeMap together with TreeSet. It will sort automatically. Of course, you could have done that manually as well but the work will be done more efficiently with the use of TreeMap. You can also use it if random access is vital for you.
Difference Between Questions
Q #25) What is the difference between Collection and collections?
Answer:
Collection | Collections |
---|---|
It is an interface. | It is class. |
The collection represents a group of objects as a single entity. | Collections define different methods of utility for collection objects. |
It is Collection Framework’s root interface. | Collections are a utility class. |
It derives Collection Framework’s data structures. | Collections contain many different static methods for aiding in manipulating the data structure. |
Q #26) How is Array different from an ArrayList?
Answer:
Differences between Array and ArrayList are given below:
Array | ArrayList |
---|---|
The array is a strongly typed class. | ArrayList is a loosely typed class. |
Array can’t be resized dynamically, its dimension is static. | ArrayList can be resized dynamically. |
An array doesn’t need boxing and unboxing of elements. | ArrayList needs boxing and unboxing of elements. |
Q #27) Differentiate between ArrayList and LinkedList.
Answer:
ArrayList | LinkedList |
---|---|
ArrayList uses the dynamic array internally for storing elements. | LinkedList implements the doubly linked list. |
ArrayList manipulation of elements is rather slow. | LinkedList manipulates its elements much faster. |
ArrayList can act solely as a List. | LinkedList can act as both List and a Queue. |
Useful for storing and accessing data. | Useful for manipulating data. |
Q #28) How is Iterable different from Iterator?
Answer:
Iterable | Iterator |
---|---|
It is Java.lang package interface. | It is Java.util package interface. |
Yields only one abstract method known as the Iterator. | It comes with two abstract methods- hasNext and next. |
Represents a series of elements that can be traversed. | Stands for objects with iteration state. |
Q #29) State the differences between Set and List.
Answer:
Set | List |
---|---|
Set implements Set interface. | The list implements the List interface. |
Set is an unordered set of elements. | The list is an ordered set of elements. |
The set doesn’t maintain the order of elements during insertion. | List retains the order of elements during insertion. |
The set doesn’t allow duplicate values. | The list allows duplicate values. |
The set does not contain any legacy class. | List contains Vector, a legacy class. |
The set allows only one null value. | No restriction on the number of null values in List. |
We cannot use ListIterator to traverse a set. | ListIterator can traverse List in any direction. |
Q #30) What is the difference between Queue and Stack?
Answer:
Queue | Stack |
---|---|
Queue works on the principle of the First-In-First-Out (FIFO) approach. | Stack works on a Last-In-First-Out (LIFO) basis. |
Insertion and deletion in the queue take place at different ends. | Insertion and deletion are performed from the same end called the top of the stack. |
Enqueue is the name of Insertion and dequeue is the deletion of elements. | Push is insertion and Pop is the deletion of elements in Stack. |
It has two pointers- one to the first element of the list (front) and one to the last (rear). | It only has one pointer pointing to the top element. |
Q #31) How are SinglyLinkedList and DoublyLinkedList different from each other?
Answer:
Singly Linked List | Doubly Linked List |
---|---|
Each node of the singly linked list consists of a data and a pointer to the next node. | A doubly linked list consists of data, a pointer to the next node, and a pointer to the previous node. |
The singly-linked list can be traversed using the next pointer. | A doubly linked list can be traversed using both previous and next pointer. |
The singly-linked list takes less space compared to a doubly-linked list. | The doubly linked list takes up a lot of memory space. |
Element access is not very efficient. | Element access is efficient. |
Q #32) How is HashMap different from HashTable?
Answer:
HashMap | HashTable |
---|---|
HashMap inherits AbstractMap class | HashTable inherits Dictionary class. |
HashMap is not synchronized. | HashTable is synchronized. |
HashMap allows multiple null values but only one null key. | HashTable does not allow a null value or key. |
HashMap is faster. | HashTable is slower than HashMap. |
HashMap can be traversed by Iterator. | HashTable cannot be traversed using iterator or enumerator. |
Q #33) List down the difference between ArrayList and Vector.
Answer:
ArrayList | Vector |
---|---|
ArrayList is non-synchronized. | Vector is synchronized. |
ArrayList is not a legacy class. | Vector is a legacy class. |
ArrayList increases size by half of ArrayList when an element is inserted beyond its size. | Vector increases its size by double when an element is inserted beyond its size. |
ArrayList is not thread-safe | Vector is a thread-safe. |
Q #34) How is FailFast different from Failsafe?
Answer:
FailFast | FailSafe |
---|---|
While iterating, no modification of a collection is allowed. | Allows modification while iterating. |
Uses original collection for traversing. | Uses a copy of the original collection. |
No extra memory required. | Needs extra memory. |
Throws ConcurrentModificationException. | No exception is thrown. |
Conclusion
These Java Collections interview questions will help you to prepare for the interview. Your preparation for the Java Collections interview must be deep and extensive so study these questions and understand the concept well.
These questions not only test your knowledge but also your presence of mind.
=> Watch Out The Simple Java Training Series Here