In this article, we will cover some of the interview questions with their justification on Java Collection framework
These are most frequently asked interview question from Java Collection framework
Read Java Collection framework concepts in detail
1. Collection :
Q) What is Collection in Java ?
- A Collection is a group of element/objects represented as single unit/entity
- Programmers can perform various operations like insertion, deletion, sorting, searching, and reversing, etc. on the Collection
Q) What is Collection framework in Java ?
- A Collection framework consists of various classes & interfaces for different operational purpose
- This is introduced in Java 1.2 version after aligning old traditional classes like Vector & Hashtable with new classes like ArrayList & HashSet
Q) Explain Java Collection framework hierarchy ?
Note:
- although, Map is listed here but it doesn’t fall under Collection umbrella;
- only reason to speak Map along with other Collection like List/Set/Queue is that, it also stores group of key-value pairs and represents as single unit/entity
Q) What are the advantages of Collection framework in Java ?
- Used to store group of objects as a single unit/entity
- Dynamically grow-able in nature
- That’s collection size increases as more number of objects added and size shrinks when deleted
- Every collection class is based on some standard data structures like for example, dynamic array for ArrayList & Vector classes and hash table for HashSet
- There are standard ready-made API’s available to operate on Collection like adding/deleting elements, etc which help to improves development efforts
Q) Why do we need Collection framework ?
- Collection is group of elements stored as a single entity or unit
- In Java 1.0 version, there are several classes to achieve above mentioned concept, but they were all arranged in ad-hoc basis
- These classes are Vector, Stack, Dictionary, Hashtable and Properties
- These classes are collectively referred as legacy classes and every method inside legacy classes is synchronized i.e.; thread-safe access in a multi-threaded environment
- With Java 1.2 version introduction, Sun (now Oracle) group came up with Collection framework putting together above legacy classes and newly introduced classes into one place (i.e.; java.util package) under the root interface java.util.Collection interface
2. List :
Q) List down all classes that implements List interface ?
- ArrayList
- LinkedList
- Vector
- Stack through Vector class, as shown in the below figure
Q) What are the differences between ArrayList & LinkedList ?
- Both classes are implementation of List interface
- Operations such as addition, removal or retrieval is very important while discussing difference between ArrayList & LinkedList
- For complete differences, read ArrayList v/s LinkedList
ArrayList | LinkedList |
To store item/elements, ArrayList uses dynamic array or dynamically re-sizing array i.e.; internal data structure | To store items/elements, LinkedList uses doubly linked list i.e.; internal data structure |
The initial capacity of ArrayList is 10 | LinkedList doesn’t have any initial capacity i.e.; just constructs empty list of size 0 |
When ArrayList exceeds its capacity, then its size increases by 50% | No such thing required in LinkedList |
When ArrayList exceeds its capacity, then internally new array is created with 50% more of the original size and
Old array data copied into new array | No such overhead, as item/element is added to end of LinkedList
Due to this, insertion is faster in LinkedList comparing with ArrayList |
Similarly, while deleting from the middle of ArrayList involves lot of shifting work | Deletion is much simpler in LinkedList, as previous and next links gets deleted and new link is formed |
Q) What are the differences between ArrayList and Vector ?
- For complete differences, read ArrayList v/s Vector
ArrayList | Vector |
ArrayList is introduced in the original collection framework in Java 1.2 version | Vector is a legacy class including Stack, Dictionary, HashTable & Properties and introduced in Java 1.0 version |
ArrayList methods are non-synchronized | All legacy collection classes are synchronized, thus Vector is synchronized (i.e.; all methods of Vector class is synchronized) |
As ArrayList is non-synchronized, hence it isn’t thread-safe. So, programmer need to handle thread-safety while working in a multi-threaded environment | As Vectror is synchronized, hence it is thread-safe. So, no need to worry while working in a multi-threaded environment, as only one thread get chance to work at any given time |
Q) What are the differences between Arrays and ArrayList ?
- Read Arrays v/s ArrayList for more details with examples
Q) How to obtain an Array from ArrayList in Collection ?
- Use toArrays(); method of Collection interface
- Read conversion of List to Arrays for complete detail with example
- Similarly, conversion of Arrays to List is possible, refer above link for example
Q) How to reverse the elements of List items in Collection ?
- Use reverse(); method of Collections class to reverse the elements of Collection items
- Pass collection items as input arguments, for which items need to be reversed
- Read How to Reverse order of elements in ArrayList for complete detail with example
Q) What will happen to List, if we add final keyword to it? Whether more elements can be added to the List ?
- Making any List as final implies that List cannot modified further
- But it doesn’t stops values to be added to List (use add() or addAll() methods of Collection interface)
- To restrict any value to be added to the List, then use Collections class’ unmodifiableList(); method
- Syntax: Collections.unmodifiableList();
Q) Whether elements can be added to below List “lst” ?
private final List<String> lst = new ArrayList<String>();
- Yes, elements can be added to List lst using add(); method of Collection/List interface of String type only, as it is bounded-type
- But further modification to declared List “lst” isn’t possible, as it is marked with final modifier
- Also, assignment can’t be changed from ArrayList to any other List implemented classes like LinkedList, Vector or Stack
- And bounded-types can’t be changed from String to any other valid types
3. Iterating :
Q) What are the different ways to iterate through List ?
- for-loop (regular)
- Enhanced for-loop
- Iterating using Iterator of Collection interface
- Iterating using ListIterator of List interface
- Iterating List using forEach() in Java 8
- Read Various ways to iterate through ArrayList – 5 ways
Q) What are the different ways to iterate through Set ?
- Enhanced for-loop (introduced in Java 1.5 version)
- Iterating using Iterator of Collection interface
- Iterating Set using forEach() in Java 8
- Read Various ways to iterate through HashSet – 3 ways
Q) What are the different ways to iterate through Map ?
- Using keySet() method and for-each loop
- Using keySet() method and Iterator interface
- Using entrySet() method and for-each loop
- Using entrySet() method and Iterator interface
- Iterating Map using forEach() in Java 8
- Read Various ways to iterate through HashMap – 5 ways
Q) What are the differences between Iterator and ListIterator ?
- For complete differences, read Iterator v/s ListIterator
- Read Iterator in detail with example & explanation
- Read ListIterator in detail with example & explanation
Iterator | ListIterator |
Iterator interface is applicable for every collection classes like ArrayList, HashSet or Hashtable | ListIterator interface is applicable only for List objects like ArrayList or LinkedList or Vector |
Here, we can iterate through collection items only in FORWARD direction | But with ListIterator, we can iterate through list items either in FORWARD or BACKWARD directions |
That is, it is unidirectional or single directional cursor | That is, it is bi-directional cursor |
Note: both Iterator introduced in Java 1.1 version and ListIterator introduced in Java 1.2 version as part Collection framework
Q) Why ListIterator introduced, when already Iterator is there to iterate over List items ?
- With Iterator, collection items can be iterated only in FORWARD direction
- To iterate on both direction i.e.; FORWARD & BACKWARD, ListIterator is introduced in Java 1.2 version
- Whereas Iterator is introduced in Java 1.1 version
- But ListIterator is limited to iterate only on List items
Q) What are the differences between Iterator, ListIterator and Enumeration ?
- For complete differences, read Iterator v/s ListIterator v/s Enumeration
- Read Enumeration in detail with example & explanation
- Read Iterator in detail with example & explanation
- Read ListIterator in detail with example & explanation
Enumeration | Iterator |
ListIterator |
This is part of Legacy collection introduced in Java 1.0 version | This is part of Collection framework introduced in Java 1.2 version | This is part of Collection framework introduced in Java 1.2 version |
Using Enumeration interface, we can enumerate only legacy classes like Hashtable or Vector or Properties | Iterator interface is applicable for every collection classes like ArrayList, HashSet or Hashtable | ListIterator interface is applicable only for List objects like ArrayList or LinkedList or Vector |
We can enumerate legacy collection items only in FORWARD direction | Here, too we can iterate through collection items only in FORWARD direction | But with ListIterator, we can iterate through list items either in FORWARD or BACKWARD directions |
That is, it is unidirectional or single directional cursor | That is, it is unidirectional or single directional cursor | That is, it is bi-directional cursor |
Q) Explain way to avoid ConcurrentModificationException, while iterating Collection items ?
- Generally, ConcurrentModificationException is thrown, if any modification is done while iterating collection items
- Collection classes introduced in Java 1.2 version like ArrayList or HashSet throws ConcurrentModificationException as it works on original copy leading throwing this exception
- To avoid this, use concurrent collection classes like CopyOnWriteArrayList, CopyOnWriteArraySet & ConcurrentHashMap introduced in Java 1.5 version as it never throws ConcurrentModificationException
- Reason: it works on cloned copy, later which is merged with original copy by JVM
Q) Which design pattern Iterator follows ?
- Iterator design pattern
Q) What is fail-safe and fail-fast Iterator in Java ?
- Read CopyOnWriteArrayList for detail with example & explanation
- Read CopyOnWriteArraySet for detail with example & explanation
- Read ConcurrentHashMap for detail with example & explanation
Fail-fast | Fail-safe |
While iterating collection items if any modification is done, then ConcurrentModificationException is thrown
This is said to be fail-fast | While iterating collection items if any modification is done and if ConcurrentModificationException is never thrown, then it is said to be fail-safe |
Generally, Collection classes introduced in Java 1.2 version like ArrayList or HashSet falls under this category | New concurrent classes introduced in Java 1.5 version is fail-safe and never throws ConcurrentModificationException |
Here, there is no concept of cloned copy. Hence, both iteration & modification happening in the same original copy leading to throwing of ConcurrentModificationException | This is because, modification happens in a separate cloned copy & later JVM merges both original with cloned copies |
Example: ArrayList, LinkedList, HashSet, TreeSet | Example: CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentHashMap |
Above listed classes comes from java.util package | Above listed classes comes from java.util.concurrent package |
Q) How to iterate over Map of ArrayList?
- Get all keys from Map using keySet() method
- Now, iterate over all keys got from Map either using enhanced for-loop or Iterator
- Using get(“key”); method of Map, get corresponding ArrayList
- Again, iterate over ArrayList to get or print all values/element stored inside ArrayList
- For complete example, read Various ways to iterate over HashMap of ArrayList in Java
- Also read Various ways to iterate through ArrayList – 5 ways
Q) How to iterate over List of HashMap?
- Iterate through List (it can be either ArrayList or LinkedList)
- In each iteration step, one HashMap will be retrieved
- Get all keys from Map using keySet() method
- Now, iterate over all keys got from Map either using enhanced for-loop or Iterator
- Using get(“key”); method of Map, get corresponding values
- For complete example, read Various ways to iterate over List of HashMap in Java
4. Set :
Q) What are the differences between List and Set ?
List | Set |
List stores elements according to insertion-order
So, insertion-order is preserved | Set stores elements in random-order, as it uses hashing technique
Insertion-order isn’t preserved |
While iterating List items, elements will be retrieved as per insertion order | While iterating Set items, elements will be retrieved in random order |
List allows duplicate elements | Set doesn’t allow duplicate elements i.e.; it stores only unique elements
Note: if same element is added again, there won’t be any compile-time or runtime error, just that add() method returns false; |
Any number of NULL object is allowed to add to the List | Maximum of one NULL is allowed |
Q) List down all classes that implements Set interface ?
Q) Which internal data structure is followed by HashSet ?
- HashSet is backed by a hash table (actually a HashMap instance) to store element/objects
Q) What are the differences between HashSet and TreeSet ? And decide which one to use ?
- Read HashSet v/s TreeSet for details with example & explanation
- Read HashSet in detail with example & explanation
- Read TreeSet in detail with example & explanation
HashSet | TreeSet |
Uses hash table to store element/objects where duplicates are NOT allowed | Uses balanced tree to store element/objects where duplicates are NOT allowed |
Insertion-order is NOT maintained, as it uses hashing technique to store element/objects | Insertion-order is NOT maintained, as element/objects are stored according to some sorting-order |
HashSet doesn’t deal with sorting order; but it can be converted to TreeSet to store element/objects in some sorting-order
TreeSet ts = new TreeSet(hashSet); | Element/objects stored in TreeSet are according to some sorting-order; it could be either default natural-sorting order or programmer defined customized sorting-order |
While iterating HashSet, we will get items in random-order | While iterating TreeSet, we will get items in sorted-order; either natural ordering or customized sorting-order |
Q) Explain NavigableSet and its advantages ?
- NavigableSet interface is a sub-interface of SortedSet interface (i.e.; NavigableSet extends SortedSet)
- To represent a group of element/objects as a single unit/entity, where duplicates aren’t allowed and element/objects are stored according to some sorting-order
- It allows only unique element/objects to be inserted
- It stores element/objects in sorting-order
- NavigableSet interface defines more specific methods for navigation purposes, in addition to inherited methods from Set/SortedSet/Collection interfaces
- This is introduced in Java 1.6 version for navigation support
Q) How many null elements can be added to Set i.e.; HashSet or TreeSet ?
- As Set maintains uniqueness w.r.t elements added to the set i.e.; either HashSet or TreeSet
- Maximum of only one null elements can be added to any Set implemented classes
- Even if 2nd null is added to set, it won’t throw any error (compile-time or runtime)
- Actually, earlier null element will be replaced by new null element
- Read HashSet in detail with example & explanation
- Read TreeSet in detail with example & explanation
Q) In which Java version, LinkedHashSet is introduced ?
- LinkedHashSet is implementation class of Set interface (i.e.; LinkedHashSet implements Set)
- This is introduced in Java 1.4 version
- LinkedHashSet uses combination of LinkedList & hash table to store element/objects
5. Queue :
Q) What are the difference between peek(), poll() & remove() methods of Queue interface ?
- Read Queue interface in detail with example & explanation
- Similarly, read PriorityQueue which is the Queue implemented class
Queue methods | Description |
Object peek(); | retrieve head element without removing from Queue
returns null, if Queue is empty |
Object poll(); | retrieve & remove head element from Queue returns null, if Queue is empty |
Object remove(); | retrieve & remove head element from Queue |
Q) List down all classes that implements Queue interface ?
- PriorityQueue
- PriorityBlockingQueue (through BlockingQueue interface)
- LinkedBlockingQueue (through BlockingQueue interface)
6. Map :
Q) List down all classes that implements Map interface ?
- HashMap
- LinkedHashMap
- WeakHashMap
- IdentityHashMap
- TreeMap (through SoretdMap –> NavigableMap)
- Hashtable
- Properties (through Hashtable)
Q) What are the different ways to get Collection views for Map interface ?
Map methods | Description |
Set keySet(); | returns set of keys from invoking map
this provides collection/set views of Map |
Collection values(); | returns collection containing values of invoking map
this provides collection/set views of Map |
Set entrySet(): | returns set of map entries of type Map.Entry
this provides collection/set views of Map |
- Read keySet() method for getting all keys from Map
- Read values() method for getting all values from Map
- Read entrySet() method for getting all entries from Map, in the form of key-values pairs
Q) In which Java version, LinkedHashMap is introduced ?
- LinkedHashMap is implementation class of Map interface (i.e.; LinkedHashMap implements Map)
- This is introduced in Java 1.4 version
- LinkedHashMap uses combination of LinkedList & hash table to store Map entries (i.e.; key-value pairs)
Q) Explain IdentityHashMap in detail ?
- IdentityHashMap is exactly same as that of HashMap with few differences
- HashMap: JVM uses equals() method to check uniqueness of keys before storing
- IdentityHashMap: JVM uses == operator to check uniqueness of keys before storing
Q) Explain WeakHashMap in detail ?
- WeakHashMap is exactly same as that of HashMap with few differences
- HashMap: If objects don’t have any reference outside of HashMap, even then objects aren’t eligible for Garbage Collection. HashMap has precedence over Garbage Collector
- WeakHashMap: If objects don’t have any reference outside of WeakHashMap, still JVM executes Garbage collection. Garbage collector has precedence over objects inside WeakHashMap. Kind of stores only weak references
Q) Explain NavigableMap and its advantages ?
- NavigableMap interface is a sub-interface of SortedMap interface (i.e.; NavigableMap extends SortedMap)
- To represent a group of key-value pairs as a single unit/entity, where duplicates keys aren’t allowed and keys are stored according to some sorting-order
- It allows only unique keys to be inserted
- Stores key-value pairs in sorting order on the basis of keys only, not values
- NavigableMap interface defines more specific methods for navigation purposes, in addition to inherited methods from Map/SortedMap interfaces
- This is introduced in Java 1.6 version for navigation support to TreeMap
Q) How Map is different from List and Set ?
- List & Set interface extends Collection interface, which stores group of objects as a single entity
- Whereas Map stores group of key-value pairs as a single entity
- Note: Map interface doesn’t extend Collection interface
Q) What are the differences between Map and Set ?
- Set stores group of objects as a single entity and duplicate objects aren’t allowed
- Map stores group of key-value pairs as a single entity where keys are unique but values can be duplciate
Q) What are the differences between HashMap and HashSet ?
HashMap | HashSet |
HashMap implements Map interface | HashSet implements Set interface |
Used to store key-value pairs using put method
Example: hm.put(key, value); | Used to store only unique objects using add method
Example: hs.add(object); |
HashMap doesn’t allow duplicate keys but values can be duplicated | HashSet doesn’t allow duplicate objects |
HashMap allows maximum of one null key but any number of NULL values allowed | HashSet allows maximum of one null object to be added |
HashMap internally uses an array of Entry<K,V> objects | HashSet internally uses HashMap to store unique objects |
Performance-wise, HashMap is faster than HashSet | Performance-wise, HashSet is slower than HashMap |
Q) What are the differences between HashMap and Hashtable ?
HashMap | Hashtable |
HashMap is introduced in collection framework in Java 1.2 version | Hashtable is a legacy class and introduced in Java 1.0 version |
HashMap is NOT synchronized | Hashtable is synchronized |
All methods of HashMap is NOT synchronized i.e.; it is not thread-safe | All methods of HashMap is synchronized i.e.; thread-safe |
Multiple threads are allowed to access | Only one thread is allowed access; other threads has to wait to get access, after obtaining lock/monitor |
Performance-wise, this is relatively high comparing with Hashtable, as there is no wait time | Performance-wise, this is relatively slow due synchronized methods as there is only one thread allowed to access, at any given point of time |
NULL insertion allowed for both keys and values | NULL insertion is not allowed for both keys and values |
Maximum of one NULL key and there is no upper limit for values | Simply, not allowed for both keys & values |
Q) What are the differences between HashMap and TreeMap ? And decide which one to use ?
HashMap | TreeMap |
Uses hash table to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowed | Uses Red-Black tree to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowed |
Insertion-order is NOT maintained, as it uses hashing technique to store key-value pairs (i.e.; map entries) | Insertion-order is NOT maintained, as key-value pairs (i.e.; map entries) are stored according to some sorting-order |
HashMap doesn’t deal with sorting-order; but it can be converted to TreeMap to store key-value pairs (i.e.; map entries) in some sorting order
TreeMap ts = new TreeMap(hashMap); | Keys in TreeMap are sorted, according to some sorting-order; it could be either default natural sorting-order or programmer defined customized sorting-order |
While iterating HashMap, we will get items in random-order | While iterating TreeMap, we will get items in sorted-order; either natural-ordering or customized sorting-order |
This is introduced in original collection framework in Java 1.2 version | This is also introduced in original collection framework in Java 1.2 version |
Key: Allows NULL insertion but maximum of only one NULL value
Value: No upper limit for NULL values against any unique key | Key: From Java 1.7 version, NULL is not allowed to insert; But with Java version than 1.6 or less, only as 1st element allowed (for keys)Value: No upper limit for NULL values against any unique key |
Q) What are the differences between HashMap and ConcurrentHashMap ?
HashMap | ConcurrentHashMap |
HashMap is not synchronized | ConcurrentHashMap is synchronized |
In multi-threaded environment, HashMap is faster than ConcurrentHashMap as multiple threads can operate
Hence, performance is high as there is no need to acquire lock | As it is synchronized, lock need to be acquired before operating, although for certain portion of the Map
Hence, performance is relatively low when comparing with HashMap |
NULL insertion is possible for key but maximum of one null key and any number of null values against any key | NULL insertion isn’t allowed for both keys and values |
While one thread iterating HashMap items, if any other thread tries to modify Map items then ConcurrentModificationException is thrown | While one thread iterating ConcurrentHashMap items, other thread are happily can modify Map items
And it never throws ConcurrentModificationException |
That’s it is fail-fast iterator | That’s it is fail-safe iterator |
This is introduced in original collection framework in Java 1.2 version | This is introduced in Java 1.5 version |
We can convert this Map item into synchronized map by using Collections class utility method
But still, only one thread is allowed to operate on Map object | There is no such need here, as it is already thread-safe and multiple threads can operate after acquiring bucket-level or segment-level locking strategies |
7. Miscellaneous :
Q) What are the differences between Comparator and Comparable ?
- Read Comparable v/s Comparator for details with example & explanation
- Read Comparable in detail with example & explanation
- Read Comparator in detail with example & explanation
Comparable interface | Comparator interface |
Present in java.lang package | Present in java.util package |
Defines only one important method i.e.;
public int compareTo(Object obj); | Defines 2 method i.e.;
public int compare(Object obj1, Object obj2); public boolean equals(Object object); |
It is basically used for default natural sorting order [DNSO] | This is preferred for customized sorting order [CSO] |
This interface need to be implemented in the same class for which sorting is required | Separate class is required to implement Comparator interface |
Elements of List can be sorted using comparable interface
Example: Collection.sort(listItems); | Elements of List can be sorted using comparator interface
Example: Collection.sort(listItems, comparator); |
String & wrapper classes’ like Integer, Double, etc implement comparable interface | There are very few classes’ which implements Comparator interface |
Q) What are the differences between Collection and Collections ?
- Collection interface is a root of Collection framework hierarchy
- List, Set & Queue interfaces extends Collection interface
- Collections (with extra s appending at the end) is a utility class for operating on Collection items
- Operation such as sorting, searching, shuffling, reversing, swapping, synchronizing, etc can be performed on collection items using Collections class’ methods
- Read Collection interface for details with example & explanation
- Read Collections class for details with example & explanation
Q) Which Collection classes are thread-safe or synchronized ?
- By default, all legacy classes introduced in Java 1.0 version are synchronized namely Vector, Hashtable, Stack, Properties, Dictionary
- And newly introduced concurrent classes in Java 1.5 version are synchronized namely ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet
Q) How to convert any un-synchronized collection classes into synchronized Collection class ?
- To convert any un-synchronized collection class to synchronized, use synchronizedCollection() method from Collections class
- But we also have, special conversion methods for List, Set or Map i.e.; synchronizedList(), synchronizedSet(), synchronizedMap()
- Examples:
Collection collection = null;
List list = null;
Set set = null;
Map map = null;
// to convert any collection class to synchronized Collection
Collections.synchronizedCollection(collection);
// to convert List class to synchronized List
Collections.synchronizedList(list);
// to convert Set class to synchronized Set
Collections.synchronizedSet(set);
// to convert Map class to synchronized Map
Collections.synchronizedMap(map);
Q) What are the ways to make or restricts any collection to read-only ?
- To restricts any collection to read-only, then use unmodifiableCollection() from Collections class
- Example:
// to restrict collection class to read-only
Collections.unmodifiableCollection(collection);
Q) What are Ordered and Sorted Collection classes in Java Collection framework ?
- Ordered Collection –> ArrayList, LinkedList, Vector, LinkedHashSet, LinkedHashMap
- Sorted Collection –> TreeSet & TreeMap
- Un-ordered Collection –> HashSet & HashMap
Q) Does enumeration interface considered legacy ?
- Yes, Enumeration interface is legacy
- It is introduced in Java 1.0 version
- Apart from Enumeration interface, below mentioned classes are considered as Legacy collection
- Legacy classes : Hashtable, Vector, Stack, & Properties classes and Dictionary abstract class
8. Java 1.5 Concurrent Collection :
Q) List down all classes introduced in Java 5 Concurrent Collection ?
Q) What is ConcurrentHashMap in Java ?
- ConcurrentHashMap is the implementation class of ConcurrentMap interface (i.e.; ConcurrentHashMap implements ConcurrentMap)
- ConcurrentHashMap uses hash table data structure to store key-value pairs (which is known as map entry)
- Allows only unique keys and there is no such restriction on values
- NULL insertion isn’t allowed for both Key/Values
- Allows concurrent access of read/update operations (i.e.; 2 or more threads can operate on same ConcurrentHashMap object simultaneously)
- For read operation, lock isn’t required
- But for update operation, lock is required but that’s only for part of the Map object (i.e.; Bucket level locking)
- Actually, bucket is divided into n-number of parts and one lock is associated with each part
- These locks are referred as concurrency-level
- ConcurrentHashMap never throws ConcurrentModificationException while 2 or more threads operating simultaneously
Q) What is CopyOnWriteArrayList ?
- CopyOnWriteArrayList is the implementation class of List interface (i.e.; CopyOnWriteArrayList implements List)
- For every modify/update operation, a new separate cloned copy is created and modification is performed on the cloned copy; while other threads can iterate over original copy
- After modification/updation, JVM takes care of merging both copies (i.e.; original and cloned copy) –> so that we get latest copy with all updation/modification
- Since, every time a new separate cloned copy is created for updation or modification. Therefore, it is suited for multi-threaded environment where there are more number of read/get operation and comparatively less update/modify operation
- While one thread iterating over original copy, other threads can modify with separate cloned copy and compiler won’t throw any ConcurrentModificationException; which isn’t case with ArrayList
- It never throws ConcurrentModificationException while 2 or more threads operating simultaneously i.e.; it is fail-safe iterator
- But, there are certain limitation too with CopyOnWriteArrayList which isn’t case with ArrayList like, while iterating CopyOnWriteArrayList, remove operation isn’t possible and compiler throws UnsupportedOperationException
- Other than above discussed points, all other properties of ArrayList are applicable for CopyOnWriteArrayList too
Q) What is CopyOnWriteArraySet ?
- CopyOnWriteArraySet is the implementation class of Set interface (i.e.; CopyOnWriteArraySet implements Set)
- Internally COWAS is implemented using COWAL
- So for every modify or update operation, a new separate cloned copy is created and modification is performed on the cloned copy; while other threads can iterate over original copy
- After modification/updation, JVM takes care of merging both copies (i.e.; original and cloned copy) –> so that we get latest copy with all updation/modification
- Since, every time a new separate cloned copy is created for updation or modification. Therefore, it is suited for multi-threaded environment where there are more read/get operation and comparatively less update/modify operation
- While one thread iterating over original copy, other threads can modify with separate cloned copy and compiler won’t throw any ConcurrentModificationException; which isn’t case with other Set implemented classes like HashSet or TreeSet
- It never throws ConcurrentModificationException while 2 or more threads operating simultaneously i.e.; it is fail-safe iterator
- But, there are certain limitation too with CopyOnWriteArraySet which isn’t case with Set implemented classes like HashSet or TreeSet like while iterating COWAS, remove operation isn’t possible and compiler throws UnsupportedOperationException
Q) Explain difference between ArrayList and CopyOnWriteArrayList ?
CopyOnWriteArrayList | ArrayList |
CopyOnWriteArrayList is synchronized or newly introduced thread-safe class | ArrayList is not synchronized |
For every update operation, a new separate cloned copy is created and there is memory & merging overhead for JVM
Hence, performance is relatively low when comparing with ArrayList | In multi-threaded environment, ArrayList is faster than CopyOnWriteArrayList as multiple threads can operate
Hence, performance is high as there is no need to acquire lock |
While one thread iterating CopyOnWriteArrayList items, other threads happily can modify, as it works on separate cloned copy
And it never throws ConcurrentModificationException | While one thread iterating ArrayList items, if any other thread tries to modify same ArrayList object then ConcurrentModificationException is thrown |
That’s it is fail-safe iterator | That’s it is fail-fast iterator |
Iterator of CopyOnWriteArrayList can perform read operation safely; while iterating through COWAL items
But as soon as, remove operation is performed, compiler throws UnsupportedOperationException | Iterator of ArrayList can perform both read and remove operations; while iterating through AL items |
Q) Difference between Synchronized Collection and Concurrent Collection?
Concurrent Collection | Synchronized Collection |
Concurrent Collection are newly introduced thread-safe class (i.e.; synchronized) | This is thread-safe version of Collection class |
Multiple threads are allowed to operate on Concurrent Collection, as it works on separate cloned copy for update/modify operations | Only one thread is allowed to operate on synchronized collection, by locking over complete list object |
While one thread iterating Concurrent Collection object, other threads happily can modify, as it works on separate cloned copy
And it never throws ConcurrentModificationException | While one thread iterating on synchronized collection object, if any other threads tries to modify same object then ConcurrentModificationException is thrown |
That’s it is fail-safe iterator | That’s it is fail-fast iterator |
There is no such restriction while iterating on Concurrent Collection
We can safely iterate outside synchronized block | While iterating synchronized Collection, make sure to iterate inside synchronized block;
Otherwise we may face non-deterministic behavior |
Iterator of Concurrent Collection can perform read operation safely; while iterating
But as soon as, remove operation is performed, compiler throws UnsupportedOperationException | Iterator of synchronized collection can perform both read and remove operations; while iterating |
Hope, you found this article very helpful. If you any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.
Happy Coding !!
Happy Learning !!