Thursday, 1 September 2016

Top 20 Collection Framework Interview Questions

Collection is the most important topic in any Java/J2EE programming interview. I have created a list of important JCF interview question and sharing the same with you. I hope it will help you . 

1.) What is Collection Framework in Java? What is root of collection interface framework?

Collection simply represent a group of Objects in java. Collection Framework is a java library that provides a unified architecture for 

working(representing, manipulating, searching and sorting etc.) with collections.

Collection interface is the root interface of collection framework.


Benefits - Collection framework makes the development easy and fast and provide different type of collection interfaces(Map, Set, List, Queue and Dqueue) and their implementations classes(ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue etc.) to make developement work easier. Collection classes implementations are optimized, So they makes out code good in quality and faster in performance.


2.) What are Collection and Collections in JCF?


Collection - Collection is root interface of JCF (Java Collection Framework).

Collections - Collections is a utility class in JCF which provides a lot of utility methods for collection classes. Like methods for sorting of collection.

3.) What are the important interfaces and classes in JCF?


The core interfaces in JCF are Collection, Set, List, Map and Queue. Other than these some important framework are SortedSet, SortedMap, ListIterator and Dqueue also.


JCF also provides implementation class for different interfaces like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue , Properties, Hashtable etc.


4.) What are List and Set and Map interfaces?


SetSet can contains unique elements only. Set doesn't maintains the order of insertion. HashSet and TreeSet are the implementation classes of Set interface.


List - List can contain duplicate elements. List is indexed based collection and maintain the order in which elements are added. ArrayList, Vector and LinkedList are the implementation classes of List interface. Vector is a legacy class and synchronized(thread-safe). Vector can be used in multi-threaded environment.


Map - Map is not a collection of objects like List and Set. Map is collection of entrySet objects which represent a key-value pair. HaspMap, HashTable and Properties are the implementation classes of Map interface. HashTable is legacy class and synchronized(thread-safe). HashTable can be used in multi-threaded environment.


5.)What is an iterator and Enumeration? What is different between them?


Iterator - Iterator is an interface in java's util package. Iterator is used to iterate over collections. Iterator have three methods which are -

  • hasNext()
  • next()
  • remove()
Enumeration - Enumeration is a legacy interface to enumerate over collections. Enumeration is used with legacy classes like Vector and Properties. Enumeration has two methods to enumerate which are - 
  • hasMoreElements( ) 
  • nextElement().
Similarities between Iterator and Enumeration -
  • Both are used to iterate over collection classes.
  • Both are designed on the basis of Iterator design pattern.
Difference between Iterator and Enumeration -
  • Enumerations can only perform read only operations(traverse and fetch), while Iterator can add or remove elements while iterating over the collection.
  • Enumerations are fail-safe while Iterators are fail-fast. That means Iterator do not allow one thread to modify a collection while some other thread is using the same. It will throw ConcurrentModificationException in that case.
  • Enumeration methods name are bigger while Iterator have shorter method names.

6.) What is the difference between Iterator and ListIterator?
  • Iterator cab be used to traverse in forward direction only while ListIterator van traverse in forward and backward direction both.
  • Iterator can be used to iterate over List and Set, but ListIterator is only specific to List.
  • Iterator can not add or update existing element, but we can add or update existing elements while using ListIterator.
  • Iterator doesn't provide indexes while traversing, but ListIterator have methods to get next and previous index while traversing.
7.) What is the difference between Vector and ArrayList?

Vector and ArrayList are two different implementations of List interface. Vector is legacy class present from Java1.1 while ArrayList was added with JCF in Java1.2. The main differences between Vector and ArrayList are -
  • Vector in Java are synchronised while ArrayList are not synchronised. Because of that ArrayList is faster than Vector.
  • Vector and ArrayList both are based on dynamic array. But after exceeding Vector make 100% increase in size while ArrayList increase its size by 50% of current size.
  • Enumeration and Iterator both can be used for traversal of Vector elements while we can only use Iterator with ArrayList.
8.) What is the difference between Array and ArrayList in Java ?
  • Array size is fixed that is defined while creating the array. After creation Array size can not be changed. But ArrayList is dynamic in size. Default size of ArrayList is 10, which is dynamically increased by 50% after exceeding the current capacity.
  • Array can store both primitive and objects while ArrayList can only store objects.
9.) What is the difference between ArrayList and LinkedList ? How to choose from them?

ArrayList and LinkedList both are implementation of List in JCF. But they have difference in their implementation and methods. Below are the main differences between ArrayList and LinkedList -
  • ArrayList uses array data structure implementation while LinkedList is implemented with Doubly Linked List data structure.
  • Insertion and deletion of elements is faster than ArrayList in LinkedList while searching is faster in ArrayList. 
When to use ArrayList - Search in ArrayList is indexed based and faster than LinkedList. So ArrayList should be used for more search and less insert/delete operation.

When to use LinkedList - LinkedList should be used for more insertion/deletion and less search operation scenarios.

10.) What is the difference between HashSet, LinkedHashSet and TreeSet ?

HashSet, LinkedHashSet and TreeSet all are implementation of Set interface. All are used to store unique values. The main differences between these three are -
  • HashSet is implemented using HashTable so HashSet does not maintain the order of elements. HashSet stores the elements in random order.
  • LinkedHashSet is implemented using HashSet and LinkedList, that's why LinkedHashSet stores the elements in insertion order.
  • TreeSet extends the SortedSet and implemented using Red-Black tree. So TreeSet stores the elements in sorted order.
11.) What is Map interface? Why Map interface doesn't extends Collection interface?

Map interface represents a collection of key-value pairs. Map interface do not extends the Collection because Map interface is designed to store data in key-value pair, where as Collection store the single objects. Map contains three different collections which are keySet, valueSet and EntrySet.

12.) What is the differences between HashTable and HashMap ?

HashTable and HashMap both are implementation of Map interface. HashTable is a legacy class while HashMap was added in Java1.2. Below are the main differences between HashTable and HashMap -

  • HashTable is synchronized while HashMap is not synchronized. So HashTable is slower than HashMap and can be used in multi-threaded environment.
  • HashTable does not allow any null key or value, while HashMap allows one null key and any number of null values.
  • HashTable can use Iterator and Enumerator both while HashMap can only be traversed with Iterator.
  • Enumerator of HashTable are not fail-fast while Iterator of HashMap is fail-fast.
13.) What is the difference between HashMap and ConcurrentHashMap ?

ConcurrentHashMap was introduced in Java5 as an alternative of HashTable. Main differences between HashMap and ConcurrentHashMap are -



  • HashMap are not synchronised while ConcurrentHashMap are synchronised.
  • HashMap allows one null key and multiple null values while ConcurrentHashMap does not allow any null key or value.
  • HashMap are faster in performance than ConcurrentHashMap.
14.) Can we convert a HashMap or HashSet in synchronised HashMap are synchronised HashSet ?

Yes, we can convert collection classes in synchronized collection classes. Collections utility class provides us methods to convert collection classes in synchronized collection classes.
  • Collections.synchronizedMap(Map) to convert HashMap in synchronized HashMap.
  • Collections.synchronizedSet(Set) for Set and Collections.synchronizedList(List) for Lists. Also provides a general method for Collection Collections.synchronizedCollection(Collection).
15.) Difference between Comparable and Comparator interfaces.

Comparable and Comparator both are used to sort a given collection. Comparable sort the collection in natural order and implemented on the class itself while Multiple comparator can be created for sorting on the basis of different parameters in the class.

For more details on Comparable and Comparator Check HERE.

16.) Which concurrent collection classes added in Java5 ? How they are different from existing collections ?

Concurrent collection classes added in Java5 are -
  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet
  • BlockingQueue etc.
These classes are alternative for synchronization of existing HashMap. ArrayList and HashSet's. These classes can be used in multithreaded environment and allow one thread to modify the collection while others are reading. Concurrent classes does not throw ConcurrentModificationException.

I Java6 also some other important concurrent classes were added like BlockingDqueue and ConcurrentSkipListMap and ConcurrentSkipListSet etc.


17.) What is BlockingQueue in JCF? 

As discussed in previous question, BlockingQueue was added in Java5. Blocking queue is implementation of Queue interface. 

BlockingQueue waits for element insertion if queue is already full and waits on retrieval if queue is empty.

Classical problem of Producer-Consumer can be resolved in very easy way using BlockingQueue, as we don't need to write synchonization and wait-notify code. It is handled by BlockingQueue.


18.) How to make a Collection read only ?


This is very important and asked in many interviews. Collections utility class provides methods for Collection, List, Set and Map to make them unmodifiable/read only. Below are the methods to make Collection classes unmodifiable- 



  • Collections.unmodifiableCollection(Collection)
  • Collections.unmodifiableList(List)
  • Collections.unmodifiableSet(Set)
  • Collections.unmodifiableMap(Map).
19.) How HashMap works in Java?

HashMap internally implemented using Array and LinkedList data structure. In Java8 LinkedList was replaced with BinaryTree. HashMap works on hashing technique.

To learn HashMap working in detail Read my article How HashMap works in Java.

20.) What is  WeakHashMap and IdentityHashMap? 

WeakHashMap 


WeakHashMap class is implementation of Map interface with weak keys. An entry in WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector. 
WeakHashMap allows null key and values to store. WeakHashMap is not synchronized.

IdentityHashMap 

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys. So when you put any Key Value pair in it the Key Object is compared using == operator. On the other hand HashMap uses equals method to determine the uniqueness of the Key.

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

These are the important Java Collection Framework interview questions. Please let me know if some are missed. I will add the same.

Check below links also-
Core Java Interview Questions - OOps and Basics
Core Java Interview Questions - String
Servlet Interview Questions
Bubble Sort Algorithm analysis and implementation in Java
Linear Search Algorithm analysis and implementation in Java
Binary Search Algorithm analysis and implementation in Java

No comments:

Post a Comment