Java collection interview questions
Collections as a topic is very vast in Java. There are lot of concepts which can be asked by an interviewer in your Java interview. But by being prepared to answer these questions, one can easily answer the frequently asked questions. My suggestion is to read the FAQ as well do some programming exercises on Java collections. Also it is a good thing to play with the programs so as to see what happens if you change some part of the code. In this article, I shall list down whole lot of Java collection interview questions. I have included questions from all the three categories of collections i.e. List, Map and Set. In addition to these, I have written questions on related concepts like iterators, ConcurrentModificationException and Comparable/Comparator interfaces.
Q.What is the difference between ArrayList and Vector in Java?
Both these classes are present in the List hierarchy and offer index based access to the elements. While Vector allows to specify the capacityIncrement in addition to initialCapacity, ArrayList class only allows initialCapacity to specified using its constructors.
Q. How does hashcode works in Java or What is hashcode?
Ans: Hashcode is the building block of hash based data structures and collection classes in Java. For every object to be used with collections like HashMap and HashSet, the hashcode is used to uniquely locate the object in memory. The use of hashcode thus results in O(1) time complexity. There is a complex algorithm used by JVM to calculate the default hashcode of an object. However, one can always override the hashcode method as per requirement. You may want to read more on how hashcode internally works in Java.
Q. What is hashcode and equals contract?
Ans: Both hashcode and equals method are present in the Object class and hence inherited by all classes in Java. When an object is used in HashMap, LinkedHashMap or HashSet collections, there is a contract called hashcode and equals contract which should be followed by that class so that the storage and retrieval of objects can be achieved. The contract says that for two equals objects, the hashcode should always be same. If this is not followed, unexpected results will be seen in the program. My advice is not to go to interview without writing a program around this contract and playing with different parts to see what happens if you break the hashcode equals contract.
Q. There are few methods defined in the Collection interface. Are all these methods supported by all collection classes?
Ans: No it is not guaranteed that all operations defined in the Collection interface be supported by all collection classes. Some collection classes provide only operations which are suitable for its type. For example a List returned by Arrays.asList(…) method is fixed length and doesn’t support add operation. When any operation is not supported by a collection class then UnsupportedOperationException is raised. It is worth noting some operations may seem to be available by API due to inheritance for super types but are not supported by all flavors of a particular type.
Q. What are Comparable and Comparator interfaces and when would you use which one?
Ans: Both these interfaces are used for comparison of objects. The final result of both is to tell whether one object is smaller, equal or larger than the other one. To do so, the methods defined in these interfaces return -ve, 0 or +ve values. You should be aware of exhaustive differences between Comparable and Comparator interfaces. While Comparable interface has compareTo method, Comparator interface has the compare method which needs to overridden when implementing these interfaces.
Regarding the suitability of when to use which, always remember that you should use Comparator for comparing objects whose class is not written by you or you don’t have access to the source code for classes (like those present in some JAR file or distributed objects). On the other hand, use Comparable interface with classes which are under your control. The classes which are part of your application and are suitable for comparison should implement the Comparable interface.
Q.Would you consider it a best practice to inherit collection classes and roll out your own version with custom behavior?
Ans: It is a good option to go for custom collection classes by inheriting the classes provided by JDK. It is good to go for them when in a large application, where a particular class has to be used in custom way repeatedly. The benefit of doing so is that it reduces the line of code in the application. The developers working on the application need to learn it once and then they can use it as and when required.
Q. Can you explain how the collection framework is structured in JDK?
Ans: There is Collection interface at the top with other interfaces and classes as its children. One exception to the Collection interface is the Map based collections hierarchy. The Map interface doesn’t extend the Collection interface, but the Set and List interfaces do extend the Collection interface. Each of the Map, Set and List interfaces are then implemented by Abstract classes namely AbstractMap, AbstractSet and AbstractList. The use of interfaces and abstract class brings in very good inheritance and contract relationship in the collections hierarchy. Then at the leaf nodes are concrete implementation of each type of collection. For example List heirarchy has various flavors including ArrayList, LinkedList and Vector. Apart from the above described interfaces, abstract classes and concrete classes, there are some helper interfaces and classes. These helper classes and interfaces include Iterator, ListIterator, Comparable and Comparator.
When using a particular collection for a purpose, apart from the suitability of the collection (like Set for no-duplicate elements), the time complexity of collection class should also be taken into consideration.
Q. What is the difference between TreeMap and TreeSet? Or How does TreeMap and TreeSet classes work in Java?
Ans: I have already written a tutorial on the internal working and difference between TreeMap and TreeSet.
Q. You mentioned that HashMap uses hashcode for storing key value pairs. Can I bring in ordering in the key value pairs?
Ans: The collection hierarchy in Java does support flexibility in terms of conversion of one collection class to another by using convenient constructors. There are helper classes like Collections and Arrays which can further make the task of sorting elements of unordered collections. I had myself written on 5 ways to sort hashmap in Java.
Q. Ok collection framework has this Collection interface which has methods like addAll, removeAll etc. Can I some how use these method to perform operations like union, intersection and difference of collections?
Ans: The set theory in mathematics defines some operations on the sets which are not limited on the type of set. In Java also we can have these set operations implemented by using the methods from Collection interface and writing our logic for operations which are not supported by these methods. Though it seems that Map interface can’t be used with other collection classes for set theory operations but it is not the case. Map based collections have a sub-element known as Entry and each Entry object comprises of one key/value pair. Thus Entry objects can be used with elements from other collection like ArrayList and HashSet for set operations. The implementation of these set operations can be achieved by the use of methods from Collection interface.