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.

You can read more in depth difference between the ArrayList and Vector classes in Java. Similar to ArrayList and Vector difference is the HashMap and Hashtable interview question.

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.

Related Posts

Java collection interview questions admin Core Java
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...
Collections as a topic is very vast in Java. There are lot of concepts which can be asked by an interviewer in your <a href="http://www.javaexperience.com/java-test-for-developers/">Java interview</a>. 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. <strong>Q.What is the difference between ArrayList and Vector in Java?</strong> 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. You can read more in depth difference between the <a href="http://www.javaexperience.com/differences-between-arraylist-and-vector/">ArrayList and Vector classes in Java</a>. Similar to ArrayList and Vector difference is the <a href="http://www.javaexperience.com/differences-between-hashmap-and-hashtable-in-java/">HashMap and Hashtable interview question</a>. <strong>Q. How does hashcode works in Java or What is hashcode?</strong> 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 <a href="http://www.javaexperience.com/java-dive-deep-into-hashcode-internals/">how hashcode internally works in Java</a>. <strong>Q. What is hashcode and equals contract?</strong> 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 <a href="http://www.javaexperience.com/hashcode-and-equals-contract/">break the hashcode equals contract</a>. <strong>Q. There are few methods defined in the Collection interface. Are all these methods supported by all collection classes?</strong> 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. <strong>Q. What are Comparable and Comparator interfaces and when would you use which one?</strong> 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 <a href="http://www.javaexperience.com/difference-between-comparable-and-comparator-interfaces/">exhaustive differences between Comparable and Comparator interfaces</a>. While Comparable interface has <a href="http://www.javaexperience.com/overriding-compareto-method-in-java/">compareTo method</a>, Comparator interface has the <a href="http://www.javaexperience.com/compare-objects-using-comparator-in-java/">compare method</a> 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. <strong>Q.Would you consider it a best practice to inherit collection classes and roll out your own version with custom behavior?</strong> Ans: It is a good option to go for <a href="http://www.javaexperience.com/inheriting-collections-to-create-custom-collections/">custom collection classes</a> 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. <strong>Q. Can you explain how the collection framework is structured in JDK?</strong> 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 <a href="http://www.javaexperience.com/exhaustive-differences-between-abstract-class-and-interface/">interfaces and abstract class</a> 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 <a href="http://www.javaexperience.com/java-how-iterators-works/">Iterator, ListIterator</a>, 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 <a href="http://www.javaexperience.com/time-complexity-of-collection-classes/">time complexity of collection class</a> should also be taken into consideration. <strong>Q. What is the difference between TreeMap and TreeSet? Or How does TreeMap and TreeSet classes work in Java?</strong> Ans: I have already written a tutorial on the internal working and <a href="http://www.javaexperience.com/difference-between-treemap-and-treeset-in-java/">difference between TreeMap and TreeSet</a>. <strong>Q. You mentioned that HashMap uses hashcode for storing key value pairs. Can I bring in ordering in the key value pairs?</strong> 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 <a href="http://www.javaexperience.com/5-ways-to-sort-hashmap-in-java-based-on-keys-or-values/">5 ways to sort hashmap in Java</a>. <strong>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?</strong> 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 <a href="http://www.javaexperience.com/perform-set-operations-using-java-collection-classes/">implementation of these set operations</a> can be achieved by the use of methods from Collection interface.
Use Case for Binary, Octal and HexaDecimal in Java
Hashcode and equals contract
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Comments

comments