Tuesday, August 10, 2021

Top 25 Java Collection Framework Interview Questions Answers for Freshers and Experienced Programmers

Interview questions from the Collection package or framework are most common in any Core Java Interview yet a tricky one. Together Collection and multithreading make any Java interview tough to crack and having a good understanding of Collection and threads will help you to excel in Java interviews. I thought about writing interview questions on the Java collection framework and important classes like ArrayList, HashMap, Hashtable, and newly added concurrent collections e.g. ConcurrentHashMap when I first wrote 10 multi-threading Interview questions but somehow this article got delayed. Though I have shared several questions individually in between.

I think the main reason for this delay could be spending a lot of time researching and preparing the mega list of core Java questions from the last 5 years.  In this article, we will see a mix of some beginners and advanced Java Collection interviews and their answers which have been asked in various Core Java interviews.

These Java Collection framework interview questions have been collected from various friends and colleagues and Answers to these interview questions can also be found by Google. BTW, if you are preparing for a Java interview then you can also take help from these Java interview courses and books, both are resources to do well in Java interviews.



    


Popular Java Collection Interview Questions Answers

Java Collection interview questions answersNow let's start with interview questions on collections. Since the collection is made of various data structures e.g. Map, Set, and List and their various implementation, mostly the interviewer checks whether the interviewee is familiar with the basics of these collections or not and whether he knows when to use Map, Set, or List. 

Based on the Role for which the interview is going on questions start with beginner’s level or more advanced level. Normally 2 to 3 years experience counted as beginners while over 5 years comes under the advanced category, we will see questions from both categories.


1. How does HashMap work in Java? (answer)
This is a Classical Java Collection interview question which I have also discussed in my earlier article on how does HashMap works in Java. This collection of interview questions is mostly asked during AVP Role interviews on Investment-Banks and has a lot of follow-up questions based on the response of the candidate like Why HashMap keys need to be immutable, what is race conditions on HashMap, and how HashMap resize in Java. For explanation and answers to these questions Please see the earlier link.



2. What is the difference between poll() and remove() method of Queue interface? (answer)
Though both poll() and remove() method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. 

If Queue is empty() then a call to remove() method will throw Exception, while a call to poll() method returns null. By the way, exactly which element is removed from the queue depends upon the queue's ordering policy and varies between different implementations, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position. 




3. What is the difference between fail-fast and fail-safe Iterators? (answer)
This is a relatively new collection of interview questions and can become a trick if you hear the terms fail-fast and fail-safe the first time. Fail-fast Iterators throw ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing, or modifying objects on the underlying collection. 

They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand, fail-safe Iterators works on copy of collection instead of the original collection



4. How do you remove an entry from a Collection? and subsequently what is the difference between the remove() method of Collection and remove() method of Iterator, which one you will use while removing elements during iteration?

Collection interface defines remove(Object obj) method to remove objects from Collection. List interface adds another method remove(int index), which is used to remove objects at a specific index. You can use any of these methods to remove an entry from Collection, while not iterating. 

Things change when you iterate. Suppose you are traversing a List and removing only certain elements based on logic, then you need to use Iterator's remove() method. This method removes the current element from Iterator's perspective. 

If you use Collection's or List's remove() method during iteration then your code will throw ConcurrentModificationException. That's why it's advised to use the Iterator remove() method to remove objects from Collection.



5. What is the difference between Synchronized Collection and Concurrent Collection? (answer)
Java 5 has added several new Concurrent Collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue, etc, which has made Interview questions on Java Collection even trickier. Java Also provided a way to get a Synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.

One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization. See the difference between Synchronized Collection and Concurrent Collection in Java for more details.



6. What is the difference between Iterator and Enumeration? (answer)
This is a beginner-level collection interview questions and mostly asked during interviews of Junior Java developers up to experience of 2 to 3 years Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.

Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify the collection object during iteration except the remove() method and throws ConcurrentModificaitonException. See Iterator vs Enumeration in Java for more differences.



7. How does HashSet is implemented in Java, How does it use Hashing? (answer)
This is a tricky question in Java because for hashing you need both key and value and there is no key for the store it in a bucket, then how exactly HashSet store element internally. Well, HashSet is built on top of HashMap. 

If you look at source code of java.util.HashSet class, you will find that that it uses a HashMap with same values for all keys, as shown below:

private transient HashMap map;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

When you call add() method of HashSet, it put entry in HashMap :

public boolean add(E e) {
  return map.put(e, PRESENT)==null;
}

Since keys are unique in a HashMap, it provides uniqueness guarantee of Set interface.




8. What do you need to do to use a custom object as a key in Collection classes like Map or Set? (answer)
The answer is: If you are using any custom object in Map as key, you need to override equals() and hashCode() method, and make sure they follow their contract. On the other hand if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals() method is consistent to compareTo() method, otherwise that collection will not follow there contacts e.g. Set may allow duplicates.




9. The difference between HashMap and Hashtable? (answer)
This is another Classical Java Collection interview asked on beginner’s level and most of Java developer has a predefined answer for this interview questions e.g. HashMap is not synchronized while Hashtable is not or hashmap is faster than hash table etc. What could go wrong is that if he placed another follow-up question like how hashMap works in Java or can you replace Hashtable with ConcurrentHashMap etc. See Hashtable vs HashMap in Java for detailed answer of this interview question.



10. When do you use ConcurrentHashMap in Java? (answer)
This is another advanced level collection interview questions in Java which normally asked to check whether the interviewer is familiar with optimization done on ConcurrentHashMap or not. ConcurrentHashMap is better suited for situation where you have multiple readers and one
Writer or fewer writers since Map gets locked only during the write operation. If you have an equal number of reader and writer than ConcurrentHashMap will perform in the line of Hashtable or synchronized HashMap.




11. What is the difference between Set and List in Java? (answer)
Another classical Java Collection interviews popular on telephonic round or the first round of interview. Most of Java programmer knows that Set doesn't allowed duplicate while List does and List maintains insertion order while Set doesn't. What is key here is to show the interviewer that you can decide which collection is more suited based on requirements.



12. How do you Sort objects on the collection? (solution)
This Collection interview question serves two purpose it not only test an important programming concept Sorting but also utility class like Collections which provide several methods for creating synchronized collection and sorting.

Sorting is implemented using Comparable and Comparator in Java and when you call Collections.sort() it gets sorted based on the natural order specified in compareTo() method while Collections.sort(Comparator) will sort objects based on compare() method of Comparator. 



13. What is the difference between Vector and ArrayList? (answer)
One more beginner level collection interview questions, this is still very popular and mostly asked in the telephonic round. ArrayList in Java is one of the most used Collection class and the most interviewers asked questions on ArrayList. See Difference between Vector and ArrayList for the answer to this interview question.



14. What is the difference between HashMap and HashSet? (answer)
This collection interview question is asked in conjunction with HashMap vs Hashtable. HashSet implements java.util.Set interface and that's why only contains unique elements, while HashMap allows duplicate values. 

In fact, HashSet is actually implemented on top of java.util.HashMap. If you look at internal implementation of java.util.HashSet, you will find that it adds elements as key on the internal map with the same values. For a more detailed answer, see HashMap vs HashSet.



15) What is NavigableMap in Java? What is a benefit over Map? (answer)
NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure. It provides methods like lowerKey() to get keys which is less than specified key, floorKey() to return keys which is less than or equal to specified key, ceilingKey() to get keys which is greater than or equal to specified key and higherKey() to return keys which is greater specified key from a Map. 

It also provide similar methods to get entries e.g. lowerEntry(), floorEntry(), ceilingEntry() and higherEntry(). Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an exsiting Map like tailMap, headMap and subMap. headMap() method returns a NavigableMap whose keys are less than specified, tailMap() returns a NavigableMap whose keys are greater than the specified and subMap() gives a NavigableMap between a range, specified by toKey to fromKey.  



16) Which one you will prefer between Array and ArrayList for Storing objects and why? (answer)
Though ArrayList is also backed up by array, it offers some usability advantage over array in Java. Array is fixed length data structure, once created you can not change it's length. On the other hand, ArrayList is dynamic, it automatically allocate a new array and copies content of old array, when it resize. Another reason of using ArrayList over Array is support of Generics.

Array doesn't support Generics, and if you store an Integer object on a String array, you will only going to know about it at runtime, when it throws ArrayStoreException. On the other hand, if you use ArrayList, compiler and IDE will catch those error on the spot. So if you know size in advance and you don't need re-sizing than use array, otherwise use ArrayList.


17) Can we replace Hashtable with ConcurrentHashMap? (answer)
Answer 3: Yes we can replace Hashtable with ConcurrentHashMap and that's what suggested in Java documentation of ConcurrentHashMap. but you need to be careful with code which relies on locking behavior of Hashtable. Since Hashtable locks the whole Map instead of a portion of Map, compound operations like if(Hashtable.get(key) == null) put(key, value) works in Hashtable but not in concurrentHashMap. instead of this use putIfAbsent() method of ConcurrentHashMap


18) What is CopyOnWriteArrayList, how it is different than ArrayList and Vector? (answer)
Answer: CopyOnWriteArrayList is a new List implementation introduced in Java 1.5 which provides better concurrent access than Synchronized List. better concurrency is achieved by Copying ArrayList over each write and replace with original instead of locking. Also CopyOnWriteArrayList doesn't throw any ConcurrentModification Exception. 

It's different than ArrayList because it's thread-safe and ArrayList is not thread-safe and it's different than Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers. Here is a nice table that compares performance of three popular List implementation ArrayList, LinkedList, and CopyOnWriteArrayList in Java:

Java questions from Collection framework



19) Why ListIterator has added() method but Iterator doesn't or Why to add() method is declared in ListIterator and not on Iterator. (answer)
Answer: ListIterator has added() method because of its ability to traverse or iterate in both directions of the collection. it maintains two pointers in terms of previous and next call and in a position to add a new element without affecting the current iteration.


20) When does ConcurrentModificationException occur on iteration? (answer)
When you remove the object using Collection's or List's remove method e.g. remove(Object element) or remove(int index), instead of Iterator's remove() method then ConcurrentModificationException occurs. 

As per Iterator's contract, if it detects any structural change in Collection e.g. adding or removing the element, once the Iterator begins, it can throw ConcurrentModificationException.  

Here are some tips to avoid ConcurrentModification in Java:

advanced Java interview questions with answers



21) Difference between Set, List and Map Collection classes? (answer)
java.util.Set, java.util.List and java.util.Map defines three of most popular data structure support in Java. Set provides uniqueness guarantee i.e.g you can not store duplicate elements on it, but it's not ordered. On the other hand List is an ordered Collection and also allowes duplicates. Map is based on hashing and stores key and value in an Object called entry. It provides O(1) performance to get object, if you know keys, if there is no collision. 

Popular impelmentation of Set is HashSet, of List is ArrayList and LinkedList, and of Map are HashMap, Hashtable and ConcurrentHashMap. Another key difference between Set, List and Map are that Map doesn't implement Collection interface, while other two does. For a more detailed answer, see Set vs List vs Map in Java


Java Collection framework interview questions with answers



22) What is BlockingQueue, how it is different than other collection classes? (answer)
BlockingQueue is a Queue implementation available in java.util.concurrent package. It's one of the concurrent Collection classes added on Java 1.5, main difference between BlockingQueue and other collection classes is that apart from storage, it also provides flow control. It can be used in inter-thread communication and also provides built-in thread safety by using a happens-before guarantee. You can use BlockingQueue to solve the Producer-Consumer problem, which is what is needed in most concurrent applications.


Few more questions for practice, try to find answers to these question by yourself:

23) How does LinkedList is implemented in Java, is it a Singly or Doubly linked list? 
Hint: LinkedList in Java is a doubly linked list.

24) How do you iterator over Synchronized HashMap, do you need to lock iteration and why?

25) What is Deque? when do you use it?


More questions:
30+ Core Java Phone Interview Questions with answers (read)
50+ Java Multithreading Questions from Last 3 years (the list)
50+ Programmer Phone Interview Questions with answers (read)

30 comments :

Aditya said...

These interview questions seems to be too common and appear in almost many interviews and that's the reason I never asked so called frequently asked or popular interview question, instead I ask something which is not so common like:

1) What is CopyOnWriteArrayList, how it is different than ArrayList and Vector?
2) Why ListIterator has add() method but Iterator doesn't or Why add() method is declared in ListIterator and not on Iterator.
3) Can we replace Hashtable with ConcurrentHashMap?
4) What is navigational Map?
5) How does LinkedList is implemented in Java, is it a Singly LinkedList or Doubly LinkedList?
6) Which one you will prefer between Array and ArrayList for Storing object and why? (Generics, dynamic growing )
7) What is BlockingQueue, how it is different than other collection classes( flow control)
8) How do you iterator over Synchronized HashMap, do you need to lock iteration and why ?
9) When does ConcurrentModificationException occur on iteration?
10) What is Deque? when do you use it ?
11) Difference between Set, List and Map Collection classes?
12) How does HashSet is implemented in Java, How does it uses Hashing ?

If anyone wants to answer this question , they must required a very good understanding of Java Collection framework which is whole purpose of these interview questions.

Prabhu said...

core java interview questions on collections are second most asked java questions after thread and String. By the way can you please share pdf version of your java collection interview for download ?

Ashwin said...

Hello Sir, Can you please share interview question from new Collection classes introduced in Java 5 and Java 6 like BlockingQue, DeQueue, NavigationalMap etc. Now days no buddy asked about List, Set or Map they ask questions on Concurrent Collections, Synchronized Collections etc.

Anonymous said...

Can you please share some Java collection intervie questions asked on Capegemini , Tech Mahindra, TCS, Patni, Mahindra Satyam, HSBC, WIPRO and Cognizant, I am making list, please help

Neva said...

I think Collection interview questions listed here are very much appear in Capegemini or Tech Mahindra interview. Difference between ArrayList and Vector has been asked to my friend on his Java interview with Wipro and TCS last month.

Prateek said...

One Java Collection Interview Question, which I have faced more often in JP Morgan, Cognizant and HSBC recently :

What do you need to do to use a custom object as key in Collection classes like Map or Set?

Answer is : If you are using any custom object in Map as key, you need to override equals() and hashCode() method, and make sure they follow there contract. On the other hand if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals() method is consistent to compareTo() method, otherwise those collection will not follow there contacts e.g. Set may allow duplicates.

Mohit said...

Hi Javin, Can you update this article to include some more tough, less popular but difficult questions based on Java Collections asked to experienced Java programmers, e.g. this is the one questions asked to me on Citibank interview :

How do you remove an entry from a Collection? and subsequently what is difference between remove() method of Collection and remove() method of Iterator, which one you will use, while removing elements during iteration.

sometime they ask this by giving you code, or asking to write code for removing objects. I used collections remove() method and ended with ConcurrentModificationException, gosh I read some of your article before.

But once again, please consider sharing some relatively new, tough, and good questions on Java collections.

Cheers
Mohit

Anonymous said...

Hello Javarevisited
Please do not give this is tricky interview question and all. we this tricky interview question that we know, please try to give solution and also give the solution in one page that's better.

Srikanth said...

"HashMap is not synchronized while hashtalbe is not "

I think you meant

"HashMap is not synchronized while hashtalbe is"

Gayatri said...

Hello Javin, Recently I was asked in a Java interview about, what is difference between poll() and remove() method, if both are used to remove object from Queue. I get confused, because, poll() also removes elements from head and remove() is used to remove object, which is passed to it. Is there any other difference between poll and remove, from Queue or DeQue perspective, which interviewer was looking?

Arkadiusz GÅ‚owacki said...

" If you have equaled number of reader and writer than ConcurrentHashMap will perform in line of hashtable or synchronized hashMap."
If you have equaled number of reader and writer than ConcurrentHashMap will perform n times better, where n will be somewhere close to number of cpu cores. Not whole ConcurrentHashMap is blocked on writes, but only some part of it. There is mechanism called lock striping. By default there are 16 different locks, one for each part of buckets, which means that 16 different writers can perform concurrently. The only operation where ConcurrentHashMap is slower than HashTable is expanding the map, because it needs to aquire 16 locks instead one.

Anonymous said...

Recently I was asked the difference between a linkedHashMap and a PriorityQueue.

Anonymous said...

The key also has to be immutable..

Anonymous said...

post the internal implementation of ArrayList i will be grateful to you....

Unknown said...

Hi Nice article. Requesting one modification in question 21. you have written "Map doesn't implement Collection interface" it should be "Map doesn't extends Collection interface".

Unknown said...

it uses a HashMap with same values for all keys - Maybe you meant for values, but not for keys?

javin paul said...

@Arturs didn't get your point. HashSet does use HashMap internally and same value, an object is used for all keys. In short, HashMap's key set is your HashSet.

Prabhakar said...

when I tried the below code I got exception mentioned in the code. Please clarify me why I got exception. Is there any relation between trimsize() and sublist() methods of arrayList

Public class Practice
{
Public static void main()
{
ArrayList pArrayList = new ArrayList(50);

pArrayList.add("PXXXXXX");
pArrayList.add("KXXXXX");
pArrayList.add("ABCD");
pArrayList.add("MNOP");
pArrayList.add("XYZ");
pArrayList.add("Test");


List subList = pArrayList.subList(2,4);

System.out.println(subList); // Printing sublist without Exception

pArrayList.trimToSize();
pArrayList.add("Extra");

System.out.println(subList); // occur Exception java.util.ConcurrentModificationException

System.out.println(pArrayList);
}
}

Anonymous said...

Great list of questions, for more Java interview questions from last 5 years, see this list of 133 Java questions with answers

Anonymous said...

Fantastic questions form Java collections topic, but see this list of Java interview questions from last 5 years to prepare all other topics, see the list

Unknown said...

9. The difference between HashMap and Hashtable? (answer)
This is another Classical Java Collection interview asked on beginner’s level and most of Java developer has a predefined answer for this interview questions e.g. HashMap is not synchronized while Hashtable is not or hashmap is faster than hash table etc. What could go wrong is that if he placed another follow-up question like how hashMap works in Java or can you replace Hashtable with ConcurrentHashMap etc. See Hashtable vs HashMap in Java for detailed answer of this interview question.

As it is written that HashMap is not synchronized while Hashtable is not ,
Its a wrong statement , it should be like :
Hashtable is synchronized, whereas HashMap is not.

Mehrdad said...

In the list given in response to question 18, the complexity of the remove() operation for a LinkedList is displayed as O(1) while get() is listed as O(n).

In java.util.LinkedList implementation, both remove() and get() operations rely on entry(i) call to navigate the linked list to get to the element at index "i".

javin paul said...

@Mehrdad, you are right in case of remove(int i) or remove(object) method, both of which requires traversal to the right element, but if you simply call the remove() method on LinkedList, it removes elements from head which is O(1) because LinkedList maintains reference of head or first element. You can see the code in java.util.LinkedList class that remove() calls the removeFirst() which just unlink the first element, hence O(1).

/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E remove() {
return removeFirst();
}

Anonymous said...

Hi Javin,Great work,your blog is the best way to brush up concepts.Thank you.
Hope you answer my question here.Hashset internally stores it's values like HashMap with equal value for all keys right?How can HashMap have duplicate key values?Am I missing something here?

javin paul said...

Hello @Anonymous, HashMap allows duplicate values, it doesn't allow duplicate key, hence it is possible to store same values for all the keys and HashSet just does that. I suggest you reading my another article How HashSet internally works in Java to get some more insights.

Anonymous said...

In 19, there is no added() method in ListIterator but add() method...

Unknown said...

when to use identityhashmap?

Rita said...

I have one confusion, if ArrayList,HashSet implements Collection Interface, why they does not implement all the methods defined as part of collection as per normal class functionality i.e if a class implements any interface, it should implement all its methods or it should be abstract. Any concrete class will implements all the methods of interface

javin paul said...

Hello Rita, they don't extend Collection directly instead there is an intermediate class like AbstractList which implement all method of Collection and then ArrayList just overrides them as per their need. Similarly you have AbstractSet class.

Unknown said...

Poll() method returns null incase que is empty
remove() method returns NoSuchElementException

Post a Comment