Saturday, November 19, 2011

Top 10 Collection Interview Questions Answers in Java

Interview questions from Collection package or framework is most common in any Core Java Interview yet a tricky one. Together Collection and multithreading makes 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 collection when I wrote 10 multi-threading Interview questions asked in Java and Top 20 Core java Interview questions answers but somehow it got delayed. In this article we will see mix of some beginners and advanced Java Collection interviews and there answers which has been asked in various Core Java interviews. These Collection interview questions have been collected from various friends and colleagues and Answers of these interview questions can also be found by Google.
    
Java Collection interview questions answersNow 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.

Java Collection Interview Questions Answers


How HashMap works in Java?
This is Classical Java Collection interview questions which I have also discussed in How HashMap works in Java. This collection interview questions is mostly asked during AVP Role interviews on Investment-Banks and has lot of followup questions based on response of interviewee e.g. Why HashMap keys needs 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.

What is difference between fail-fast and fail-safe Iterators?
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


What is difference between Synchronized Collection and ConcurrentCollection?
Java5 has added several new ConcurrentCollection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc, which has made Interview questions on Java Collection even trickier. Java Also provided way to get Synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.One Significant difference is that ConccurentCollections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization. See Difference between SynchronizedCollection and ConcurrentCollection in Java for more details.



What is difference between Iterator and Enumeration?
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 Enumeraiton in Java for more differences.


Difference between HashMap and Hashtable?
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 hashtalbe is not or hashmap is faster than hashtable etc. What could go wrong is that if he placed another followup 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.

When do you use ConcurrentHashMap in Java?
This is another advanced level collection interview questions in Java which normally asked to check whether 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 write operation. If you have equaled number of reader and writer than ConcurrentHashMap will perform in line of hashtable or synchronized hashMap.

What is difference between Set and List in Java?
Another classical Java Collection interview popular on telephonic round or 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 interviewer that you can decide which collection is more suited based on requirements.

How do you Sort objects on collection?
This Collection interview question serves two purpose it not only test an important programming concept Sorting but Also utilty 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 natural order specified in CompareTo method while Collections.sort(Comparator) will sort objects based on compare() method of Comparator. See Sorting in Java using Comparator and Comparable for more details.


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


What is difference between HashMap and HashSet?
This collection interview questions is asked in conjunction with hashmap vs hashtable. See HashMap vs HashSet for detail Answer.


Interview Questions you may like
10 Spring Interview Questions Answers for J2EE developers
Please share with your friends if like this article

12 comments:

Anand said...

Nice one Javin. Some more collection interview questions can be found Here

Anand

Anonymous said...

very good questions on collection

Anonymous said...

Great posting!!!!

-AmitM

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.

Rajveer said...

Answer 1 - 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 its different than Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers.

Answer 2: :ListIterator has add() method because of its ability to traverse or iterate in both direction of collection. it maintains two pointers in terms of previous and next call and in position to add new element without affecting current iteration.

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

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.

Post a Comment