40 Java Collections Interview Questions and Answers

Java Collections Framework are the fundamental aspect of java programming language. It’s one of the important topic for java interview questions. Here I am listing some important questions and answers for java collections framework. I will keep on adding more questions to this post as and when I will find something that should be here, so you might want to bookmark this post for future purpose too.

  1. What are Collection related features in Java 8?
  2. What is Java Collections Framework? List out some benefits of Collections framework?
  3. What is the benefit of Generics in Collections Framework?
  4. What are the basic interfaces of Java Collections Framework?
  5. Why Collection doesn’t extend Cloneable and Serializable interfaces?
  6. Why Map interface doesn’t extend Collection interface?
  7. What is an Iterator?
  8. What is difference between Enumeration and Iterator interface?
  9. Why there is not method like Iterator.add() to add elements to the collection?
  10. Why Iterator don’t have a method to get next element directly without moving the cursor?
  11. What is different between Iterator and ListIterator?
  12. What are different ways to iterate over a list?
  13. What do you understand by iterator fail-fast property?
  14. What is difference between fail-fast and fail-safe?
  15. How to avoid ConcurrentModificationException while iterating a collection?
  16. Why there are no concrete implementations of Iterator interface?
  17. What is UnsupportedOperationException?
  18. How HashMap works in Java?
  19. What is the importance of hashCode() and equals() methods?
  20. Can we use any class as Map key?
  21. What are different Collection views provided by Map interface?
  22. What is difference between HashMap and Hashtable?
  23. How to decide between HashMap and TreeMap?
  24. What are similarities and difference between ArrayList and Vector?
  25. What is difference between Array and ArrayList? When will you use Array over ArrayList?
  26. What is difference between ArrayList and LinkedList?
  27. Which collection classes provide random access of it’s elements?
  28. What is EnumSet?
  29. Which collection classes are thread-safe?
  30. What are concurrent Collection Classes?
  31. What is BlockingQueue?
  32. What is Queue and Stack, list their differences?
  33. What is Collections Class?
  34. What is Comparable and Comparator interface?
  35. What is difference between Comparable and Comparator interface?
  36. How can we sort a list of Objects?
  37. While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?
  38. How can we create a synchronized collection from given collection?
  39. What are common algorithms implemented in Collections Framework?
  40. What is Big-O notation? Give some examples?
  41. What are best practices related to Java Collections Framework?
  42. What is Java Priority Queue?
  43. Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?
  44. Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];

Java Collections Interview Questions Answers

  1. What are Collection related features in Java 8?

    Java 8 has brought major changes in the Collection API. Some of the changes are:

    1. Java Stream API for collection classes for supporting sequential as well as parallel processing
    2. Iterable interface is extended with forEach() default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because it’s argument Consumer is a function interface.
    3. Miscellaneous Collection API improvements such as forEachRemaining(Consumer action) method in Iterator interface, Map replaceAll(), compute(), merge() methods.
  2. What is Java Collections Framework? List out some benefits of Collections framework?

    Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.
    Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package.
    Some of the benefits of collections framework are;

    • Reduced development effort by using core collection classes rather than implementing our own collection classes.
    • Code quality is enhanced with the use of well tested collections framework classes.
    • Reduced effort for code maintenance by using collection classes shipped with JDK.
    • Reusability and Interoperability
  3. What is the benefit of Generics in Collections Framework?

    Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
    This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way.

  4. What are the basic interfaces of Java Collections Framework?

    Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.

    Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.

    List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.

    A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

    Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

  5. Why Collection doesn’t extend Cloneable and Serializable interfaces?

    Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don’t.
    A lot of the Collection implementations have a public clone method. However, it does’t really make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation.
    The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.
    So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.

  6. Why Map interface doesn’t extend Collection interface?

    Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.
    If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.

  7. What is an Iterator?

    Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

  8. What is difference between Enumeration and Iterator interface?

    Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.
    Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method names have been improved to make it’s functionality clear.

  9. Why there is not method like Iterator.add() to add elements to the collection?

    The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.

  10. Why Iterator don’t have a method to get next element directly without moving the cursor?

    It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

  11. What is different between Iterator and ListIterator?

    • We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.
    • Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.
    • ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
  12. What are different ways to iterate over a list?

    We can iterate over a list in two different ways – using iterator and using for-each loop.

    		List&lt;String&gt; strList = new ArrayList&lt;&gt;();
    		//using for-each loop
            for(String obj : strList){
                System.out.println(obj);
            }
            //using iterator
            Iterator&lt;String&gt; it = strList.iterator();
            while(it.hasNext()){
                String obj = it.next();
                System.out.println(obj);
            }
    

    Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.

  13. What do you understand by iterator fail-fast property?

    Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

  14. What is difference between fail-fast and fail-safe?

    Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe.
    Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
    Check this post for CopyOnWriteArrayList Example.

  15. How to avoid ConcurrentModificationException while iterating a collection?

    We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
    Check this post for ConcurrentHashMap Example.

  16. Why there are no concrete implementations of Iterator interface?

    Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
    This allows collection classes to chose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.

  17. What is UnsupportedOperationException?

    UnsupportedOperationException is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework java.util.Collections.UnmodifiableCollection throws this exception for all add and remove operations.

  18. How HashMap works in Java?

    HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods.

    When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.

    When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. Below image will explain these detail clearly.

    java-hashmap-entry-impl

    The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 32 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.

  19. What is the importance of hashCode() and equals() methods?

    HashMap uses Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.

    Similarly all the collection classes that doesn’t store duplicate data use hashCode() and equals() to find duplicates, so it’s very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.

    • If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
    • If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.
  20. Can we use any class as Map key?

    We can use any class as Map Key, however following points should be considered before using them.

    • If the class overrides equals() method, it should also override hashCode() method.
    • The class should follow the rules associated with equals() and hashCode() for all instances. Please refer earlier question for these rules.
    • If a class field is not used in equals(), you should not use it in hashCode() method.
    • Best practice for user defined key class is to make it immutable, so that hashCode() value can be cached for fast performance. Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability.
      For example, let’s say I have a class MyKey that I am using for HashMap key.

      //MyKey name argument passed is used for equals() and hashCode()
      MyKey key = new MyKey("Pankaj"); //assume hashCode=1234
      myHashMap.put(key, "Value");
      
      // Below code will change the key hashCode() and equals()
      // but it's location is not changed.
      key.setName("Amit"); //assume new hashCode=7890
      
      //below will return null, because HashMap will try to look for key
      //in the same index as it was stored but since key is mutated, 
      //there will be no match and it will return null.
      myHashMap.get(new MyKey("Pankaj")); 
      

      This is the reason why String and Integer are mostly used as HashMap keys.

  21. What are different Collection views provided by Map interface?

    Map interface provides three collection views:

    1. Set keySet(): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
    2. Collection values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
    3. Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

I will keep on adding more questions on java collections framework as and when I found them, if you found it useful please share it with others too, it motivates me in writing more like these. :)

Please let me know if I have missed any important question, I will include that to list.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *