Java Collections Interview Question and Answers

Q1.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: VectorStack,HashtableArray. 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

 Q2. Name the core Collection classes.

  • AbstractCollection– Implements most of the Collection interface.
  • AbstractList– Extends AbstractCollection and implements List interface.
  • AbstractSequentialList– Extends AbstractList to provide sequential access.
  • ArrayList– Extends AbstractList to provide dynamic array implementation.
  • LinkedList– Extends AbstractSequentialList to implement a linked list.
  • AbstractQueue– Extends AbstractCollection and implements Queue interface.
  • ArrayDeque– Resizable-array implementation of the Deque interface.
  • PriorityQueue– Extends AbstractQueue to provide a priority-based queue.
  • AbstractSet– Extends AbstractCollection and implements Set interface.
  • HashSet– Extends AbstractSet backed by a HashTable (actually a HashMap instance).
  • LinkedHashSet– Extends HashSet to provide insertion order interation.
  • TreeSet– Extends AbstractSet (and implements NavigableSet interface) to provide sorted set.
  • EnumSet– Extends AbstractSet for use with Enum elements.

 Q3. 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. It also adds up to runtime benefit because the bytecode instructions that do type checking are not generated.

Q4. What is HashMap and Map?
Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.

Q5. What change does autoboxing bring to Collection?
Since we know that collection cannot store primitive types, only references. Before the introduction of autoboxing/unboxing in JDK5, if you wanted to strore primitive value like int in a collection, it had to be wrapped in an Integer class manually. While retrieving the value it had to be cast manually into its primitive type.
Collection still store only references but autoboxing/unboxing facilitate it to happen automatically, with no need to wrap it manually.

List<Integer> tempList = new ArrayList<Integer>();
// Storing in collection using autoboxing
tempList.add(1);
// wrapping primitive int 2 to Integer manually, with out autoboxing
tempList.add(new Integer(2));

Q6. What are the basic interfaces of Java Collections Framework?
1.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.
2.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.
3.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.
4.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.

Q7. Difference between HashMap and HashTable? Compare Hashtable vs HashMap?
Both Hashtable and HashMap provide key-value access to data. The Hashtable is one of the original collection classes in Java (also called as legacy classes). HashMap is part of the new Collections Framework, added with Java 2, v1.2. There are several differences between HashMap and Hashtable in Java as listed below

  • The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
  • HashMap does not guarantee that the order of the map will remain constant over time. But one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable.
  • HashMap is non synchronized whereas Hashtable is synchronized.
  • Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn’t. So this could be a design consideration.

Q8. What is for-each style loop
Another feature which was added to Collection with JDK 5 is for-each style loop. Any collection which wants to be the target of the “for-each loop” statement has to implement iterable interface.
Using for-each loop is easier than constructing the iterator to iterate over the collection and can be used in most of the cases rather than using the iterator loop.
If you have a list of Strings, that can be iterated using for-each loop like this.
for(String city : cityList){    System.out.println(“Name ” + city);}

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

Q10.What is a diamond operator?
Diamond operator let the compiler infer the type arguments for the generic classes. It is added in Java 7.
As Example – Before JDK7 if we had to define a Map using String as both Key and Value we had to write it like this –
Map<String, String> cityMap = new HashMap<String, String>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>) known as diamond operator
Map<String, String> cityMap = new HashMap<>();

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

Q12.What are the changes in Collections framework in Java 8?
There are several changes in Collections Framework in Java 8 mostly influenced by the inclusion of Lambda expression in Java 8 –

  • Stream API– Stream can be obtained for Collection via the stream() and parallelStream() methods;
    As exp if you have a list of cities in a List and you want to remove the duplicate cities from that list it can be done as

cityList = cityList.stream().distinct().collect(Collectors.toList());

  • ForEach loopwhich can be used with Collection. Spliterators which are helpful in parallel processing where several threads can itearate/process part of the collection.
  • New methods are added to Collections like replaceAll, getOrDefault, putIfAbsent in Map.
  • HashMap, LinkedHashMapand ConcurrentHashMap.implementation is changed to reduce hash collisions. Instead of linked list a balanced tree is used to store the entries after a certain threshold is reached.

Q13. What is fail-fast property?
At high level – Fail-fast is a property of a system or software with respect to
its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are
usually designed to stop normal operation rather than attempt to continue a possibly-flawed process.
When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: “failing immediately and visibly” sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production.
In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown.
It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown. 

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

Q15. What is ForEach statement added in Java 8?
Java 8 has added a functional style lopping to the Collections. Real advantage of this loop is when it is used on a stream with the chain of functional methods. If you have a Map<String, String> then it can be looped using ForEach statement like this –
Set<Map.Entry<String, String>> valueSet = cityMap.entrySet();
valueSet.forEach((a)->System.out.println(“Key is ” + a.getKey() + ” Value is ” + a.getValue()));

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

Q17. What is RandomAccess interface?
RandomAccess interface is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
Note that using it with a sequential access list like LinkedList will result in taking more time to access a particular element.

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

Q19. Which collection classes implement random access interface?
In Java.util package the classes that implement random access interface are – ArrayList, CopyOnWriteArrayList, Stack, Vector.

Q20.  How can we make Hashmap synchronized?
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);

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

Q22. What is the difference between Collection and Collections?
Collection is an interface which is the root of the Collections framework, as you can see in question#2, List, Set and Queue are the interfaces that extend the Collection interface.
Collections is a utility class with static methods that operate on or return Collections. It provides several methods like sort, reverse, synchronizedCollection, binarySearch etc.

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

Q24. What all Collection classes are inherently thread-safe?
In the initial Collection classes like Vector, HashTable and Stack all the methods were synchronized to make these classes thread safe.
Later implementations starting from Java 1.2 were not synchronized.
Classes in java.util.concurrent package like ConcurrentHashMap, CopyOnWriteArrayList also provides thread safety but with a different implementation that doesn’t require making all the methods synchronized.

Q25. 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<String> strList = new ArrayList<>();
//using for-each loop
for(String obj : strList){
System.out.println(obj);
}
//using iterator
Iterator<String> 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.

Q26. How can we synchronize a collection OR how to make a collection thread-safe?
Collections class has several static methods that return synchronized collections. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap – has one static factory method.

public static <T> Collection<T> synchronizedCollection(Collection<T> c);
public static <T> Set<T> synchronizedSet(Set<T> s);
public static <T> List<T> synchronizedList(List<T> list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);
Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.

Q27. Where will you use Vector and where will you use ArrayList?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than
the synchronized one

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

Q29. How to make a Collection Class immutable?
Collections class provides static method to make a Collection unmodifiable. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap – has one static factory method.
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c);public static <T> Set<T> unmodifiableSet(Set<? extends T> s);public static <T> List<T> unmodifiableList(List<? extends T> list);public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<? extends T> s);public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m);

Q30. 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 package are fail-fast whereas collection classes in are fail-safe. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.

Q31. How ArrayList works internally in Java?
Basic data structure used by ArrayList to store objects is an array of Object class, which is defined like –
transient Object[] elementData;
When we add an element to an ArrayList it first verifies whether it has that much capacity in the array to store new element or not, in case there is not then the new capacity is calculated which is 50% more than the old capacity and the array is increased by that much capacity (Actually uses Arrays.copyOf which returns the original array increased to the new length)

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

Q33. How to add elements to an ArrayList?

  • List provides a method add(E e)which appends specified element to the end of the list. Using add(E e) method will mean keep adding elements sequentially to the list.
  • Another add method – add(int index, E element)inserts the specified element at the specified position in this list.
  • Third method addAll(int index, Collection<? extends E> c)inserts all of the elements in the specified collection into this list, starting at the specified position.

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

Q35. Does ArrayList allow duplicate elements?
Yes. List allows duplicate elements to be added.

Q36. What is UnsupportedOperationException?
is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework throws this exception for all and operations.

Q37.Does ArrayList allow null?
In ArrayList any number of nulls can be added.

Q38. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting.
So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.

Summary
Review Date
Reviewed Item
Great post. I referred this site for interview. Hope I'll be selected
Author Rating
51star1star1star1star1star