Sunday, November 19, 2017

Interview questions from 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 interview. I thought about writing interview questions on 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 me spending a lot of time for researching and preparing the mega list of core Java questions from 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 of these interview questions can also be found by Google. BTW, if you are preparing for Java interview then you can also take help from Java Programming Interview Exposed, an excellent resource to do well in Java interviews.

Good Java Collection Interview Questions Answers

Now let's start with interview questions on collections. Since collection is made of various data structures e.g. Map, Set and List and there various implementation, mostly interviewer checks whether interviewee is familiar with basics of these collections or not and whether he knows when to use Map, Set or List. Based on Role for which interview is going on questions starts with beginner’s level or more advanced level. Normally 2 to 3 years experience counted as beginners while over 5 years comes under advanced category, we will see questions from both categories.

This is Classical Java Collection interview questions which I have also discussed in my earlier article how does HashMap works in Java. This collection 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 interviewee e.g. Why HashMap keys need to be immutable, what is race conditions on HashMap and how HashMap resize in Java. For explanation and answers of these questions Please see 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 queue's ordering policy and varies between different implementation, 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 relatively new collection interview questions and can become trick if you hear the term fail-fast and fail-safe first time. Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on 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 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 object at specific index. You can use any of these method 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 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 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 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.

This is a beginner level collection interview questions and mostly asked during interviews of Junior Java developer 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 collection object during iteration except 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 Mapprivate 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.

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.

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.

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.

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.

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.

This collection interview questions 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 internal implementation of java.util.HashSet, you will find that it adds element as key on internal map with 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 object 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.

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 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 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. Its different than ArrayList because its 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 which compares performance of three of popular List implementation ArrayList, LinkedList and CopyOnWriteArrayList in Java:

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 direction 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 current iteration.

20) When does ConcurrentModificationException occur on iteration? (answer)

When you remove object using Collection's or List's remove method e.g. remove(Object element) or remove(int index), instead of Iterator's remove() method than ConcurrentModificationException occurs. As per Iterator's contract, if it detect any structural change in Collection e.g. adding or removing of the element, once Iterator begins, it can throw ConcurrentModificationException. Here are some tips to avoid ConcurrentModification in Java.

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

22) What is BlockingQueue, how it is different than other collection classes? (answer)

BlockingQueue is a Queue implementation available injava.util.concurrentpackage. It's one of the concurrent Collection class added on Java 1.5, main difference betweenBlockingQueue 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 happens-before guarantee. You can use BlockingQueue to solve Producer Consumer problem, which is what is needed in most of concurrent applications.

26 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.

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.

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.

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.

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.

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.

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?

" 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.

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, 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(); }

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?

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.