Java Collection Interview Questions: Java collections are a set of classes and interfaces provided by Java to manipulate data in various ways, such as storing and retrieving data in arrays, lists, and maps. Java collections are crucial to Java programming and are widely used in Java-based enterprise applications. As such, Java Collection interview questions are crucial to Java developer interviews.
These interview questions are designed to assess a candidate’s knowledge and proficiency in using Java collections, including their advantages and disadvantages, the different types of collections, and their practical applications in programming. In this context, this article presents some commonly asked Java Collection interview questions that can help Java developers prepare for interviews and better understand the Java collection framework.
Java Collection Classes Framework
ArrayList (java.util.ArrayList)
- extends java.util.AbstractList and implements java.util.List
- uses the dynamic array to store elements inside ArrayList
- size increases by 50% of the current array size when ArrayList exceeds its capacity
- allows inserting/add duplicate elements
- maintains insertion order
- accessing elements is faster (as we can use the index to access any elements)
- manipulation, i.e., delete is very slow due to the shifting of elements
- ArrayList is non-synchronized
LinkedList (java.util.LinkedList)
- extends java.util.AbstractList and implements java.util.List & java.util.Deque
- uses a dynamic array to store elements inside LinkedList
- allows inserting/add duplicate elements
- maintains insertion order
- manipulation, i.e., delete is very faster as no shifting is required (the links break, and a new link is formed while deleting any element from LinkedList)
- LinkedList is non-synchronized
Vector (java.util.Vector)
- extends java.util.AbstractList and implements java.util.List & java.util.Deque
- uses a grow-able array to store elements
- size increases by 100% of the current array size when Vector exceeds its capacity
- allows inserting/add duplicate elements
- maintains insertion order
- Vector is legacy, and it is synchronized
Difference Between Vector vs. ArrayList
Vector | ArrayList |
---|---|
Vector is legacy (including other 4 viz., HashTable, Stack, Dictionary, Properties) | ArrayList is introduced in Java 1.2 |
All legacy collection classes are synchronized. Thus Vector is synchronized | ArrayList is not synchronized (need to make sure while working in a multi-threaded environment) |
Performance-wise vector is slower comparing with ArrayList due to synchronization | This is comparatively faster as it is non-synchronized |
Vector increases its size by 100% of the current array when its capacity exceeds | ArrayList increases its size by 50% of the current array when its capacity exceeds |
Both Iterator & Enumeration can be used to iterate items/elements inside Vector | The only Iterator is allowed to iterate items/elements inside ArrayList |
HashSet (java.util.HashSet)
- extends java.util.AbstractSet and implements java.util.Set
- uses the hashtable to store elements inside HashSet
- allows only unique elements (doesn’t allow duplicates, if any duplicate is encountered, then it is overridden)
- insertion order is not maintained, i.e., items/elements order is random while iterating
- permits null element
- HashSet is non-synchronized
- But it can be easily synchronized using Collections class, i.e., Collections.synchronizedSet(HashSet)
- HashSet is fail-fast –> throws ConcurrentModificationException is modified by any other means than HashSet’s own remove() method
LinkedHashSet (java.util.LinkedHashSet)
- extends java.util.HashSet and implements java.util.Set
- allows only unique elements (doesn’t allow duplicates, if any duplicate is encountered, then it is overridden)
- allows null element (if more than one is inserted, still it will contain only one null element)
- insertion order is maintained (in the order they are inserted)
TreeSet (java.util.TreeSet)
- extends java.util.SortedSet and implements java.util.NavigableSet
- allows only unique elements (doesn’t allow duplicates, if any duplicate is encountered, then it is overridden)
- allows null element (if more than one is inserted, still it will contain only one null element)
- It sorts the elements and maintains ascending order
List vs. Set
- A list allows duplicate items/elements
- The set allows only unique items/elements (if the same element inserted again, still it will contain just one element with that value)
PriorityQueue (java.util.PriorityQueue)
- Maintains FIFO order, i.e., orders in the PriorityQueue are in FIFO fashion
- FIFO –> First-In-First-Out
- Important methods of PriorityQueue is poll(), peek(), remove(), head()
HashMap (java.util.HashMap)
- extends java.util.AbstractMap and implements java.util.Map
- HashMap stores key\value pairs
- allows only unique elements
- maximum of only-one null key is allowed (but it can have any number of null values corresponding to a key)
- maintains no order
- HashMap is not synchronized
- But it can be easily synchronized using Collections class, i.e., Collections.synchronizedMap(hashMap)
LinkedHashMap (java.util.LinkedHashMap)
- extends java.util.HashMap and implements java.util.Map
- LinkedHashMap stores key\value pairs
- allows only unique elements
- maximum of only-one null key is allowed (but it can have any number of null values corresponding to a key)
- maintains insertion order (based on Key)
- LinkedHashMap is not synchronized
- Note: very similar to HashMap except maintaining insertion order
TreeMap (java.util.TreeMap)
- extends java.util.AbstractMap and implements java.util.NavigableMap
- TreeMap stores the key\value pair
- allows only unique elements
- The null key is not allowed (but it can have any number of null values corresponding to the key)
- maintains ascending order (based on Key)
- TreeMap is not synchronized
- Note: very similar to LinkedHashMap except maintaining ascending order
Hashtable (java.util.Hashtable)
- extends java.util.Dictionary and implements java.util.Map
- HashTable stores key\value pairs
- allows only unique elements
- The null key is not allowed, and also null value is not allowed
- HashTable is synchronized, i.e., thread-safe
- Doesn’t maintain order (while iterating)
HashTable vs. HasMap
HashTable | HashMap |
---|---|
HashTable is legacy (including other 4 viz., Vector, Stack, Dictionary, Properties) | HashMap is introduced in Java 1.2 |
All legacy collection classes are synchronized. Thus HashTable is synchronized | HashMap is not synchronized (need to make sure while working in a multi-threaded environment) |
Performance-wise HashTable is slower comparing with HashMap due to synchronization | This is comparatively faster, as it is non-synchronized |
HashTable neither allows null key or null values | HashMap allows only one null key (although it allows multiple null values corresponding to a key) |
Both Iterator & Enumeration can be used to iterate over HashTable items/elements | The only Iterator is allowed to iterate over HashMap items/elements |
Collection Sorting
We should always check 2 important interfaces while dealing with the collection framework in Java. Those are
- Comparable
- Comparator
Comparable vs Comparator
Comparable | Comparator |
---|---|
Comparable belongs to the java.lang package | Comparator belongs to java.util package |
Provides compareTo() method to sort items/elementsSignature: public int compareTo(To); | Provides compare() method to sort items/elementsSignature: public int compare(T o1, T o2); |
This is used for single-sorting over the collection items/elements | This is used for multiple-sorting over the collection items/elements |
The original class needs to implement java.lang.Comparable interfaces affecting original class | A separate new class implements java.lang.Comparator interfaces don’t affect original class |
Static method “sort(List)” of Collections class is used to sort collection items/elementsSignature: Collections.sort(List list); | Static method “sort(List, Comparator)” of Collections class is used to sort collection items/elementsSignature: Collections.sort(List list, Comparator CMP); |
Collection Interview Questions Java
Q) What is Collection in Java?
- A Collection is a group of element/objects represented as a single unit/entity
- Programmers can perform various operations like insertion, deletion, sorting, searching, and reversing, etc. on the Collection
Q) What is the Collection framework in Java?
- A Collection framework consists of various classes & interfaces for the 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 the Java Collection framework hierarchy?
Note: although, Map is listed here it doesn’t fall under Collection umbrella; the only reason to speak Map along with other Collection like List or Set or Queue is that, it also stores a group of key-value pairs and represents a single unit/entity
Q) What are the advantages of the Collection framework in Java?
- Used to store a group of objects as a single unit/entity
- Dynamically grow-able in nature, i.e., 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, the dynamic array for ArrayList & Vector classes and hashtable for HashSet
- There are standard ready-made API’s available to operate on Collection like adding/deleting elements, etc. which helps to improve the development efforts
Q) Why do we need a Collection framework?
- The collection is a group of elements stored as a single entity or unit
- In Java 1.0 version, there are several classes to achieve the above-mentioned concept, but they were all arranged on an ad-hoc basis
- These classes are Vector, Stack, Dictionary, Hashtable, and Properties
- These classes are collectively referred to as legacy classes, and every method of 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
Collection Class List
Q) List down all classes that implement List interface?
- ArrayList
- LinkedList
- Vector
- Stack
Q) What are the differences between the ArrayList & LinkedList?
- Operations such as addition, removal or retrieval is very important while discussing the difference between ArrayList & LinkedList
- For complete differences, read ArrayList v/s LinkedList
ArrayList | LinkedList |
---|---|
To store item/elements, ArrayList uses the dynamic array or dynamically re-sizing array, i.e., an internal data structure | To store items/elements, LinkedList uses a doubly-linked list, i.e., an internal data structure |
The initial capacity of ArrayList is 10 | LinkedList doesn’t have any initial capacity, i.e., just constructs an 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 an internally new array is created with 50% more of the original size andOld array data copied into the new array | No such overhead, as item/element is added to end of LinkedListDue to this, insertion is faster in LinkedList comparing with ArrayList |
Similarly, while deleting from the middle of ArrayList involves a lot of shifting work | Deletion is much simpler in LinkedList, as previous and next links get deleted, and a new link is formed |
Q) What are the differences between ArrayList & 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, the programmer needs to handle thread-safety while working in a multi-threaded environment | As Vector is synchronized, hence it is thread-safe. So, no need to worry while working in a multi-threaded environment, as only one thread gets the chance to work at any given time |
Q) What are the differences between Arrays & ArrayList?
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 the order of elements in ArrayList for complete detail with example
Q) What will happen to List if we add a final keyword to it? Whether more elements can be added to the list?
- Making any List as final implies that List cannot modify further
- But it doesn’t stop 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(); the method
- Syntax: Collections.unmodifiableList();
Iterating In Java
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 the keySet() method and an 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 & ListIterator?
- For complete differences, read Iterator v/s ListIterator
- Read Iterator in detail for 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 a FORWARD direction | But with ListIterator, we can iterate through list items either in FORWARD or BACKWARD directions |
That is, it is a unidirectional or single-directional cursor | That is, it is a bi-directional cursor |
Note: both Iterator & 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 a FORWARD direction
- To iterate in 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 & Enumeration?
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 The FORWARD direction | Here, too we can iterate through collection items only in the FORWARD direction | But with ListIterator, we can iterate through list items either in forwarding or BACKWARD directions |
That is, it is a unidirectional or single-directional cursor | That is, it is a unidirectional or single-directional cursor | That is, it is a ba i-directional cursor |
Q) Explain the 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 the cloned copy, later which is merged with an original copy by JVM
Q) Which design pattern Iterator follows?
- Iterator design pattern
Q) What is a 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 the cloned copy. Hence, both iteration & modification happening in the same original copy leading to the 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 | The above-listed classes come from java.util.concurrent package |
Q) How to iterate over the Map of ArrayList?
- Get all keys from the Map using the keySet() method
- Now, iterate over all keys got from Map either using enhanced for-loop or Iterator
- Using get(“key”); method of Map, get respective ArrayList
- Again, iterate over ArrayList to get or print all values/element stored in ArrayList
- For a 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 the List of HashMap?
- Iterate through a list (it can be either ArrayList or LinkedList)
- In each iteration step, one HashMap will be retrieved
- Get all keys from the Map using the keySet() method
- Now, iterate over all keys got from Map either using enhanced for-loop or Iterator
- Using get(“key”); method of Map, get respective values
- For a complete example, read Various ways to iterate over List of HashMap in Java
Set In Java
Q) What are the differences between List & Set?
List | Set |
---|---|
List stores elements according to insertion order, 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 |
A list allows duplicate elements | Set doesn’t allow duplicate elements, i.e., it stores only unique elementsNote: if the same element is added again, there won’t be any compile-time or runtime error, just that add() method returns false; |
Any number of the NULL object is allowed to add to the List | Maximum of one NULL is allowed |
Q) List down all classes that implement the Set interface?
- HashSet
- LinkedHashSet
- TreeSet
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 & 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 the hash table to store element/objects where duplicates are NOT allowed | Uses the balanced tree to store element/objects where duplicates are NOT allowed |
Insertion order is NOT maintained, as it uses the 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 orderTreeSet 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 & 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 element 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, an earlier null element will be replaced by the 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 an implementation class of Set interface (i.e.; LinkedHashSet implements Set)
- This is introduced in Java 1.4 version
- LinkedHashSet uses the combination of LinkedList & hash table to store element/objects
Queue In Java
Q) What are the difference between peek(), poll() & remove() methods of Queue interface ?
- Read Queue interface in detail for 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 the head element from Queue returns null if the Queue is empty |
Object remove(); | retrieve & remove the head element from Queue |
Q) List down all classes that implement the Queue interface?
- PriorityQueue
- PriorityBlockingQueue (through BlockingQueue interface)
- LinkedBlockingQueue (through BlockingQueue interface)
Map In Java
Q) List down all classes that implement 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 the 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 the keySet() method for getting all keys from the Map
- Read values() method for getting all values from Map
- Read entrySet() method for getting all entries from Map, in the form of key-value pairs
Q) In which Java version, LinkedHashMap is introduced?
- LinkedHashMap is an implementation class of Map interface (i.e.; LinkedHashMap implements Map)
- This is introduced in Java 1.4 version
- LinkedHashMap uses the combination of LinkedList & hash table to store Map entries (i.e.; key-value pairs)
Q) Explain IdentityHashMap in detail?
- IdentityHashMap is exactly the 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 the 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. The garbage collector has precedence over objects inside WeakHashMap. Kind of stores only weak references
Q) Explain NavigableMap & 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 & Set?
- List & Set interface extends Collection interface, which stores a group of objects as a single entity
- Whereas Map stores a group of key-value pairs as a single entity
- Note: Map interface doesn’t extend Collection interface
Q) What are the differences between Map & 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 duplicate
Q) What are the differences between HashMap & HashSet?
- Read HashMap v/s HashSet for details with example & explanation
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 a maximum of one null key but any number of NULL values allowed | HashSet allows a 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 & 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 have 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 to 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 & TreeMap? And decide which one to use?
HashMap | TreeMap |
---|---|
Uses the hash table to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowed | Uses the 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 a 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 orderTreeMap 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 the original collection framework in Java 1.2 version | This is also introduced in the original collection framework in Java 1.2 version |
Key: Allows NULL insertion but a maximum of only one NULL 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 less than 1.6, 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 & ConcurrentHashMap?
HashMap | ConcurrentHashMap |
---|---|
HashMap is not synchronized | ConcurrentHashMap is synchronized |
In a multi-threaded environment, HashMap is faster than ConcurrentHashMap as multiple threads can operateHence, performance is high as there is no need to acquire the ock | As it is synchronized, the lock needs to be acquired before operating, although for certain portion of the MapHence, performance is relatively low when comparing with HashMap |
NULL insertion is possible for the key but a 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 a fail-fast iterator | That’s it is a fail-safe iterator |
This is introduced in the original collection framework in Java 1.2 version | This is introduced in Java 1.5 version |
We can convert this Map item into the synchronized map by using the Collections class utility method but still, only one thread is allowed to operate on a 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 |
Q) What are the differences between Comparator & Comparable?
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 needs to be implemented in the same class for which sorting is required | A 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 & Collections?
- Collection interface is a root of Collection framework hierarchy
- List, Set & Queue interfaces extend Collection interface
- Collections (with extras appending at the end) is a utility class for operating on Collection items
- An 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 synchronize, use synchronized collection() 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 the unmodifiable collection() from Collections class
- Example:
// to restrict collection class to read-only Collections.unmodifiableCollection(collection);
Q) What are Ordered and Sorted Collection classes in the 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
- Hashtable, Vector, Stack, & Properties classes and Dictionary abstract class
Java 5 Concurrent Collection
Q) List down all classes introduced in Java 5 Concurrent Collection?
- ConcurrentHashMap
- CopyOnWriteArrayList
- CopyOnWriteArraySet
Q) What is ConcurrentHashMap in Java ?
- ConcurrentHashMap is the implementation class of ConcurrentMap interface (i.e.; ConcurrentHashMap implements ConcurrentMap)
- ConcurrentHashMap uses a 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 and values
- Allows concurrent access to reading and update operations (i.e.; 2 or more threads can operate on the same ConcurrentHashMap object simultaneously)
- For the read operation, the lock isn’t required
- But for an update operation, the lock is required but that’s only for part of the Map object (i.e.; Bucket level locking)
- Actually, the bucket is divided into n-number of parts and one lock is associated with each part
- These locks are referred to 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 or update operation, a new separate cloned copy is created and modification is performed on the cloned copy; while other threads can iterate over an original copy
- After modification or updating, JVM takes care of merging both the copies (i.e.; original and cloned copy) –> so that we get the latest copy with all updation or modification
- Since every time a new separate cloned copy is created for updating or modification. Therefore, it is suited for the multi-threaded environment where there are more number of reading/get operation and comparatively less update/modify operation
- While one thread iterating over the original copy, other threads can modify with the 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 a fail-safe iterator
- But, there are a certain limitation too with CopyOnWriteArrayList which isn’t cased with ArrayList like, while iteratingCopyOnWriteArrayList, 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 an original copy
- After modification or updation, JVM takes care of merging both the copies (i.e.; original and cloned copy) à so that we get the latest copy with all updation or modification
- Since every time a new separate cloned copy is created for updation or modification. Therefore, it is suited for the multi-threaded environment where there are more read/get operation and comparatively less update/modify operation
- While one thread iterating over the original copy, other threads can modify with the 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 a fail-safe iterator
- But, there are a certain limitation too with CopyOnWriteArraySet which isn’t cased 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 & 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 a memory & merging overhead for JVMHence, performance is relatively low when comparing with ArrayList | In a multi-threaded environment, ArrayList is faster than CopyOnWriteArrayList as multiple threads can operateHence, performance is high as there is no need to acquire the lock |
While one thread iterating CopyOnWriteArrayList items, other threads happily can modify, as it works on separately cloned copy and it never throws ConcurrentModificationException | While one thread iterating ArrayList items, if any other thread tries to modify the same ArrayList object then ConcurrentModificationException is thrown |
That’s it is a fail-safe iterator | That’s it is a fail-fast iterator |
An iterator of CopyOnWriteArrayList can perform read operation safely; while iterating through COWAL items but as soon as, remove operation is performed, the compiler throws UnsupportedOperationException | An iterator of ArrayList can perform both read and remove operations; while iterating through |
Q) Difference between Synchronized Collection & Concurrent Collection?
Concurrent Collection | Synchronized Collection |
---|---|
Concurrent Collection are newly introduced thread-safe class (i.e.; synchronized) | This is a thread-safe version of Collection class |
Multiple threads are allowed to operate on Concurrent Collection, as it works on a separate cloned copy for update/modify operations | Only one thread is allowed to operate on a synchronized collection, by locking over complete list object |
While one thread iterating Concurrent Collection object, other threads happily can modify, as it works on separately cloned copy and it never throws ConcurrentModificationException | While one thread iterating on a synchronized collection object, if any other threads try to modify the same object then ConcurrentModificationException is thrown |
That’s it is a fail-safe iterator | That’s it is a fail-fast iterator |
There is no such restriction while iterating on Concurrent CollectionWe can safely iterate outside the synchronized block | While iterating synchronized Collection, make sure to iterate inside the synchronized block; Otherwise, we may face non-deterministic behavior |
An iterator of Concurrent Collection can perform read operation safely; while iteratingBut as soon as, remove operation is performed, the compiler throws UnsupportedOperationException | An iterator of a synchronized collection can perform both read and remove operations; while iterating |
Leave a Reply