Prepare for your next interview with these top 45+ Java Collections questions. Ace your Java coding interviews!
The questions given below are the most frequently asked question in IT Industries nowadays. Check out the summary of the most frequently asked questions categorized by Beginner, Intermediate, and advanced level in most of the IT industries. It doesn’t mean that these questions will actually be asked during your interview process, but yeah you can get a sense of what companies might ask you. If you want to add questions to this list — feel free to write in the comments/Response section.
Important: Please prepare all the questions so you can be confident when you need to answer any questions.
Cover Image Credits: Java collections interview questions | Image by Author
Java Collections Interview Question Categories…
* Beginner Level Questionaries (0–2 years experience)
* Intermediate Level Questionaries (1–3 years experience)
* Advanced level Questionaries (3+ Experienced)
You may also like, Top Angular Interview Questions and Answers for 2024
Beginner Level Questionaries (0–2 years experience)
In most of the IT industries, they are asking about Basic core java concepts or basic collections-related questions to check the ability and how practical are you with java theory.
1. What is Collection? What is a Collections Framework? What are pros and cons of the Java Collections Framework?
Collection: A collection (also called a container) is an object that groups multiple elements into a single unit.
Collections Framework: The collection framework provides a unified architecture for manipulating and representing collections.
Pros/Benefits of Collections Framework :
1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.
Cons/Disadvantages of collections framework:
1. It must cast to the correct type.
2. It can’t be done compile-time type checking.
A Java collection framework provides an architecture to store and manipulate a group of objects. A Java collection framework includes the following:
- Interfaces: Interface in Java refers to the abstract data types. They allow Java collections to be manipulated independently from the details of their representation. Also, they form a hierarchy in object-oriented programming languages.
- Classes: Classes in Java are the implementation of the collection interface. It basically refers to the data structures that are used again and again.
- Algorithm: Algorithm refers to the methods which are used to perform operations such as searching and sorting, on objects that implement collection interfaces. Algorithms are polymorphic in nature as the same method can be used to take many forms or you can say perform different implementations of the Java collection interface.
2. What is the difference between Collection and Collections?
The Collection is an interface while Collections is a java class, both are present in java.util package and part of the java collections framework.
You can find the major difference (like type, extends, static methods) and similar points between collection and collections here.
This question has been used to test the knowledge of the Java Collections Framework. Make sure you go through this question before appearing for the interview.
Collection vs Collections — java interview questions | Image by Author
3. Which collection classes are synchronized or thread-safe?
Vector, Stack, Hashtable, Properties and can be used in a multi-threaded environment because they are synchronized classes (or thread-safe).
If you say anything, let’s say for example “vector” -> then the interviewer will ask you about Vector. (Understand the psychology)
4. Describe Collection Tree or Collection interface.
By Ervinn at en.Wikibooks [CC BY-SA 3.0 ], from Wikimedia Commons
The list of core collection interfaces are: just mention the important ones
Important: Collection, Set, Queue, List, Map
Other interfaces also on the list: SortedSet, SortedMap, Deque, ListIterator, etc.
Collection interface and classes | Image from Edureka
The above image is quite easier to remember easily. Honestly, I recommend this image to everyone!
5. What is the difference between Map and Set?
Map object has unique keys each containing some value, while Set contains only unique values.
6. What is the difference between List and Set?
Set contains only unique elements while List can contain duplicate elements.
Set is unordered while the List is ordered. List maintains the order in which the objects are added.
7. How to reverse the List in Collections?
There is a built-in reverse method in the Collections class. reverse(List list) accepts the list as a parameter.
Collections.reverse(listobject);
8. What are the classes implementing Set and List interface?
Class implementing Set interface: HashSet, TreeSet
Class implementing List interface: ArrayList, Vector, LinkedList
9. What is the difference between Queue and Stack?
The Queue is a data structure that is based on FIFO ( first in first out ) property. An example of a Queue in the real-world is buying movie tickets in the multiplex or cinema theaters.
The Stack is a data structure that is based on LIFO (last in first out) property. An example of Stack in the real-world is the insertion or removal of CD from the CD case.
10. Which design pattern followed by Iterator?
It follows the iterator design pattern. An iterator design pattern provides us to navigate through the collection of objects by using a common interface without letting us know about the underlying implementation.
Enumeration is an example of an Iterator design pattern.
Bonus Que: Difference between String, String Buffer, String Builder
11. Which methods you need to override to use any object as a key in HashMap?
To use any object as a key in HashMap, it needs to implement equals()
and hashCode()
method.
12. What is the difference between Iterator and Enumeration?
The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn’t.
Hence, using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read-only interface as it can only traverse the objects and fetch it.
13. What is an iterator?
The Iterator is an interface. It is found in java.util package. It provides methods to iterate over any Collection.
14. How to convert the array of strings into the list?
Arrays class of java.util package contains the method asList() which accepts the array as a parameter.So, your code will be something like this snippet,
String[] wordArray = {“Abraaa” , “kaaa” , “Daabraaaa”}; List wordList = Arrays.asList(wordArray);
15. When to use interface and abstract class?
You can find the best answer here about when to use Interface or Abstract class.
Intermediate Level Questionnaires (1–3 years experience)
These are common questions that are mostly favorited by the interviewers all the time. Prepare these questions before appearing for the interview, good luck.
1. How Hashmap works internally in java?
You can answer as “On the base of Hashing techniques”. It will make a good impression on the interviewer and so they might not ask you to explain about full internal working!
Hashing in its simplest form is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties.
A true hash function must follow this rule –
“Hash function should return the same hash code each and every time when the function is applied on same or equal objects. In other words, two equal objects must produce the same hash code consistently.”
Anyway, you must be aware of “Internal working of HashMap”.
You can check out the full article here: How HashMap Works Internally?
2. What is the difference between ArrayList, LinkedList, Vector and Stack?
Difference between ArrayList vs LinkedList vs Vector vs Stack
3. What is the difference between Iterator and List Iterator.
Using Iterator we can traverse the list of objects in the forward direction. But ListIterator can traverse the collection in both directions that are forward as well as backward.
4. What is the difference between peek(), poll() and remove() method of the Queue interface?
- Both poll() and remove() methods are used to remove the head object of the Queue. The main difference lies when the Queue is empty().
- If the Queue is empty then the poll() method will return null. While in similar case , remove() method will throw NoSuchElementException .
- peek() method retrieves but does not remove the head of the Queue. If the queue is empty then the peek() method also returns null.
5. What is the difference between HashMap and Hashtable?
It is one of the most popular collections interview questions for java developers. Make sure you go through this once before appearing for the interview.
Main differences between HashMap and Hashtable are :
- HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
- HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe.
6. What is the difference between Array and ArrayList in Java?
This question checks whether the student understands the concept of the static and dynamic array. Some main differences between Array and ArrayList are :
- An array is static in size while ArrayList is dynamic in size.
- An array can contain primitive data types while ArrayList can not contain primitive data types.
Array vs ArrayList Difference — java interview questions
Bonus Question: What is the difference between LinkedList and ArrayList in Java?
The main differences between LinkedList and ArrayList are:
- LinkedList is the doubly linked list implementation of the List interface, while, ArrayList is the resizable array implementation of the List interface.
- LinkedList can be traversed in the reverse direction using the descendingIterator() method provided by the Java API developers, while, we need to implement our own method to traverse ArrayList in the reverse direction.
7. What is the difference between HashSet and TreeSet?
The main differences between HashSet and TreeSet are :
- HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
- HashSet can store the null object while TreeSet can not store the null object.
Here you can find the comparison of all Sets (All in one)
Java all set comparison and differences | java interview questions
8.Arrange the following in the ascending order (performance): HashMap, Hashtable, ConcurrentHashMap, and Collections.SynchronizedMap
Hashtable < Collections.SynchronizedMap < ConcurrentHashMap < HashMap
9.What is the difference between HashMap and ConcurrentHashMap?
This is also one of the most popular java collections interview questions. Make sure this question is on your to-do list before appearing for the interview.
The main differences between HashMap and ConcurrentHashMap are:
- HashMap is not synchronized while ConcurrentHashMap is synchronized.
- HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values.
10. Write java code showing insertion, deletion, and retrieval of HashMap object?
Do it yourself (DIY), if found any difficulty or doubts then please mention it in the comments.
11. What are Comparable and Comparator interfaces? List the difference between them?
Just remember, .compareTo() method is not in Comparator.
12. Why Map interface does not extend the Collection interface in Java Collections Framework?
One liner answer: Map interface is not compatible with the Collection interface.
Explanation: Since Map requires a key as well as value, for example, if we want to add key-value pair then we will use put(Object key, Object value). So there are two parameters required to add an element to the HashMap object. In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet, keySet as well as other appropriate methods which have just different views from the Collection interface.
13. When to use ArrayList and LinkedList in the application?
ArrayList has a constant time search operation O(1). Hence, ArrayList is preferred when there are more get() or search operation.
Insertion, Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.
14. Write the code for iterating the list in different ways in java?
There are two ways to iterate over the list in java :
- using Iterator
- using for-each loop
15. What is the default capacity of mostly used java collections (like ArrayList and HashMap)?
Make sure you understand the difference between the terms size and capacity.
Size represents the number of elements stored currently. Capacity indicates the maximum number of elements a collection can hold currently.
Default capacity of ArrayList: 10
Default capacity of HashMap: 16
16. Why are multiple inheritances not supported in Java?
This is a really tough question to answer because your answer may not satisfy the Interviewer, in most cases Interviewer is looking for specific points and if you can bring them, they would be happy.
- Ambiguity around Diamond problem
A foo() / B foo() C foo() / D foo()
In my opinion, even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.
Sometimes if you give this reason to the interviewer he asks if C++ can support multiple inheritances then why not Java. In that case, tell below second reason,
- multiple inheritances do complicate the design and create problems during casting, constructor chaining, etc.
- java avoids this ambiguity by supporting single inheritance with interfaces.
Advanced level Questionnaires (3+ Experienced)
Whether you have experience of 3 years or more than that, a company will hire you if you have hands-on experience with working with java and familiar with the core concepts, because as your experience increases, your financial demands will increase too. The company can afford you if you are within their budget and have good skills. Prepare the below questions before appearing for the interview.
1. How HashSet works internally in java?
A Java HashSet class represents a set of elements (objects).
- It does not guarantee the order of elements.
- It is achieved by storing elements as keys with the same value always.
- It constructs a collection that uses a hash table for storing elements.
- It contains unique elements.
- It inherits the AbstractSet class.
- It also implements the Set interface.
- It uses a technique to store elements is called hashing.
- HashSet uses HashMap internally in Java.
- [Important Iterator] HashSet does not have any method to retrieve the object from the HashSet. There is only a way to get objects from the HashSet via Iterator.
- HashSet has default initial capacity = 16.
- HashSet has default loadfactor = 0.75 or 75%
- The capacity may increase automatically when more elements to be store.
You can find the mechanism/ Internal working of HashSet here.
2. How HashMap Works Internally?
The reason behind adding this question again is to make sure you must be aware of it, Once you explain the HashSet — The interviewer may ask you about the internal working of HashMap. They can also ask more deeply about collision scenarios too.
3. What is the difference between Fail-Fast iterator and Fail-Safe iterator?
This is one of the most popular interview questions for the higher experienced java developers.
The main differences between Fail-fast and Fail-safe iterators are:
- Fail-fast throws ConcurrentModificationException while Fail-safe does not.
- Fail-fast does not clone the original collection list of objects while Fail-safe creates a copy of the original collection list of objects.
4. What is hash-collision in Hashtable? How it was handled in Java?
In Hashtable, if two different keys have the same hash value then it leads to hash-collision. A bucket of type LinkedList used to hold the different keys of the same hash value.
5. What is EnumSet in Java?
EnumSet is a specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified explicitly or implicitly when the set is created.
The iterator never throws ConcurrentModificationException and is weakly consistent.
#Advantage over HashSet:
All basic operations of EnumSet execute in constant time. It is most likely to be much faster than the HashSet counterparts.
It is a part of the Java Collections Framework since JDK 1.5.
6. How do you use a custom object as a key in Collection classes like HashMap?
- If one is using the custom object as a key then one needs to override the
equals()
andhashCode()
method and one also need to fulfill the contract. - If you want to store the custom object in the SortedCollections like SortedMap then one needs to make sure that
equals()
method is consistent with thecompareTo()
method. - If inconsistent, then the collection will not follow their contracts, Because of that Sets may allow duplicate elements and the contract fails!
#Contract of hashCode() and equals() method
- If
object1.equals(object2)
, thenobject1.hashCode() == object2.hashCode()
should always be true. - If
object1.hashCode() == object2.hashCode()
is true does not guaranteeobject1.equals(object2)
7. What are concurrentCollectionClasses?
Since jdk1.5, Java Api developers had introduced a new package called java.util.concurrent that has thread-safe collection classes as they allow collections to be modified while iterating. The iterator is fail-safe that is it will not throw ConcurrentModificationException.
Some examples of concurrentCollectionClasses are:
1. ConcurrentHashMap
2. CopyOnWriteArrayList
8. How do you convert a given Collection to SynchronizedCollection?
One line code will work for you: Collections.synchronizedCollection(Collection collectionObj)
— will convert a given collection to a synchronized collection.
9. How you can sort Arraylist objects?
One liner answer will work for you:
Collections.sort(yourList)
Or you can say the steps like,
- Implement the Comparable interface for the given class
- Now to compare the objects by a particular key, we will override the obj1.compareTo(obj2)
- Then call method
Collections.sort(yourList)
10. How to sort ArrayList in descending order?
Collections.sort(arraylist, Collections.reverseOrder());
Bonus Question: What are common algorithms used in the Collections Framework?
- Common algorithms used for
searching
andsorting
. For example, a red-black algorithm is used in the sorting of elements in TreeMap. - Most of the algorithms are used for the List interface but few of them are applicable for all kinds of Collection.
11. What is UnsupportedOperationException?
This exception is thrown to indicate that the requested operation is not supported.
For example, If you call add()
or remove()
method on the readOnly collection. We know readOnly collection can not be modified. Hence, UnsupportedOperationException will be thrown.
12. How to make Collections readOnly?
We can make the Collection readOnly
by using the following lines code:
Collections.unmodifiableCollection(Collection c)
Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
13. Why is String immutable or Final in Java?
There are many factors to make it final and Immutable in java.
- String Constant Pool: If the String is mutable, changing the string with one reference will lead to the wrong value for the other references.
- Synchronization and concurrency: making String immutable automatically makes them thread-safe thereby solving the synchronization issues.
- Class Loading:
String
is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state). - Security: parameters are typically represented as
String
in network connections, database connection URLs, usernames/passwords, etc. If it were mutable, these parameters could be easily changed. - Caching: when the compiler optimizes your String objects, it seems that if two objects have the same value (a=’Rax’, and b=’Rax’) and thus you need only one string object (for both
a
andb
, these two will point to the same object).
14. Why char array is preferred to store passwords than String in Java?
String is immutable and it goes to the string pool. Once written, it cannot be overwritten. That means once you’ve created the String if another process can dump memory, there’s no way (aside from reflection) you can get rid of the data before garbage collection kicks in.
This is a security concern — but even using char[]
only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.
With plain String
you have much higher chances of accidentally printing the password to logs, monitors, or some other insecure place. char[]
is less vulnerable.
public static void main(String[] args) {
Object pw = "Password";
System.out.println("String: " + pw);
pw = "Password".toCharArray();
System.out.println("Array: " + pw);
}
It will actually print:
String: Password
Array: [C@5829428e
Because of the security concern it is better to store password as a character array.
15. Why wait and notify is declared in Object class instead of Thread?
Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanisms between two threads in Java. And Object class is the correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized.
Remember synchronized and wait to notify are two different areas and don’t confuse that they are the same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait
and notify
are communication mechanisms between two threads.
Locks are made available per Object basis, which is another reason wait and notify is declared in Object class rather than Thread class.
16. Can you override the static method in Java? if I create the same method in the subclass is it a compile-time error?
No, you can not override static method in Java but it’s not a compile-time error to declare the exact same method in a subclass, That is called method hiding in Java. We can only hide the static method in Java.
17. Why do you think we need Java collections? (Rarely asked)
The Java collection framework provides the developers to access prepackaged data structures as well as algorithms to manipulate data.
18. Check if Brackets are paired or not in the given expression using Stack / Deque.
You can find the full explained answer here.
If you find any question that must be added in this list feel free to add in the comment section.
Wrapping up...
I obtain an immense amount of satisfaction from helping others attain their goals and reach their potential through technology. Even if you wish to reach out and say "Hello", I sincerely appreciate all of the wonderful correspondence I receive each day from readers. You all enrich my life, and I hope I am able to do the same for you all as well.
If you find joy and value in what I do, please consider supporting my work with a donation — however much you can afford, it means and helps more than you can imagine.
You can give tips too using Buy me a coffee.
Discover more from 9Mood
Subscribe to get the latest posts sent to your email.
0 Comments