Top 100 Java Collection Interview Questions and Answers (Part 2)

Java Collection Interview Questions and Answers part 2 walks you through Java collection framework. It provides an architecture to store and manipulate a group of objects. A Java collection framework includes the following: Interfaces, Classes, Algorithm.

27.How will you copy elements from a Source List to another list?
There are two options to copy a Source List to another list.
Option 1: Use ArrayList constructor

Option 2: Use Collection.copy()
To use Collections.copy() destination list should be of same or larger size than source list.

Collections.copy() does not reallocate the capacity of destination List if it does not have enough space to contain all elements of source List. It throws IndexOutOfBoundsException.
The benefit of Collection.copy() is that it guarantees that the copy will happen in linear time. It is also good for the scenario when we want to reuse an array instead of allocating more memory in the constructor of ArrayList.
One limitation of Collections.copy() is that it can accept only List as source and destination parameters.171. What are the Java Collection classes that implement List interface?
Java classes that implement List interface are:

  • AbstractList
  • AbstractSequentialList
  • ArrayList
  • AttributeList
  • CopyOnWriteArrayList
  • LinkedList
  • RoleList
  • RoleUnresolvedList
  • Stack
  • Vector

28.What are the Java Collection classes that implement Set interface?
Java classes that implement Set interface are:

  • AbstractSet
  • ConcurrentSkipListSet
  • CopyOnWriteArraySet
  • EnumSet
  • HashSet
  • JobStateReasons
  • LinkedHashSet
  • TreeSet

29.What is the difference between an Iterator and ListIterator in Java?
Iterator and ListIterator are two interfaces in Java to traverse data structures. The differences between these two are:


  • 1. ListIterator can be used to traverse only a List. But Iterator can be used to traverse List, Set, and Queue etc.
  • 2. An Iterator traverses the elements in one direction only. It just goes. ListIterator can traverse the elements in two directions i.e. backward as well as forward directions.
  • 3. Iterator cannot provide us index of an element in the Data Structure. ListIterator provides us methods like nextIndex() and previousIndex() to get the index of an element during traversal.
  • 4. Iterator does not allow us to add an element to collection while traversing it. It throws ConcurrentModificationException. ListIterator allows use to add an element at any point of time while traversing a list.
  • 5. An existing element’s value cannot be replaced by using Iterator. ListIterator provides the method set(e) to replace the value of last element returned by next() or previous() methods.

30. What is the difference between Iterator and Enumeration?
Both Iterator and Enumeration are interfaces in Java to access Data Structures. The main differences between these are:

  • 1. Enumeration is an older interface. Iterator is a newer interface.
  • 2. Enumeration can only traverse legacy collections. Iterator can traverse both legacy as well as newer collections.
  • 3. Enumeration does not provide remove() method. So we cannot remove any element during traversal. Iterator provides remove() method.
  • 4. Iterator is a fail-fast interface, it gives ConcurrentModificationException if any thread tries to modify an element in the collection being iterated. Enumeration is not fail-fast.
  • 5. Method names in Iterator are shorter than in an Enumeration.

31.What is the difference between an ArrayList and a LinkedList data structure?
Main differences between ArrayList and LinkedList data structures are:


  • 1. Data Structure: An ArrayList is an indexed based dynamic array. A LinkedList is a Doubly Linked List data structure.
  • 2. Insertion: It is easier to insert new elements in a LinkedList, since there is no need to resize an array. Insertion in ArrayList is O(n), since it may require resizing of array and copying its contents to new array.
  • 3. Remove elements: LinkedList has better performance in removal of elements than ArrayList.
  • 4. Memory Usage: LinkedList uses more memory than ArrayList, since it has to maintain links for next and previous nodes as well.
  • 5. Access: LinkedList is slower in accessing an element, since we have to traverse the list one by one to access the right location.

32.What is the difference between a Set and a Map in Java?
Main differences between a Set and a Map in Java are:

  • 1. Duplicate Elements: A Set does not allow inserting duplicate elements. A Map does not allow using duplicate keys, but it allows inserting duplicate values for unique keys.
  • 2. Null values: A Set allows inserting maximum one null value. In a Map we can have single null key at most and any number of null values.
  • 3. Ordering: A Set does not maintain any order of elements. Some of sub-classes of a Set can sort the elements in an order like LinkedHashSet. A Map does not maintain any order of its elements. Some of its sub-classes like TreeMap store elements of the map in ascending order of keys.

33.What is the use of a Dictionary class?
The Dictionary class in Java is used to store key-value pairs. Any non-null object can be used for key or value. But we cannot insert a null key or null object in Dictionary. Dictionary class is deprecated now. So it should not be used in newer implementations.

34.What is the default size of load factor in a HashMap collection in Java?
Default value of load factor in a HashMap is 0.75.

35.What is the significance of load factor in a HashMap in Java?
A HashMap in Java has default initial capacity 16 and the load factor is 0.75f (i.e. 75% of current map size). The load factor of a HashMap is the level at which its capacity should be doubled.
For example, in a HashMap of capacity 16 and load factor .75. The capacity will become 32 when the HashMap is 75% full. Therefore, after storing the 12th key– value pair (16 * .75 = 12) into HashMap, its capacity becomes 32.

36.What are the major differences between a HashSet and a HashMap?
The main difference between a HashSet and a HashMap are:

  • 1. Base class: A HashSet class implements the Set interface. Whereas a HashMap class implements the Map interface.
  • 2. Storage: A HashSet is used to store distinct objects. A HashMap is used for storing key & value pairs, so that these can be retrieved by key later on.
  • 3. Duplicate Elements: A HashSet does not allow storing duplicate elements. A HashMap also does not allow duplicate keys. But we can store duplicate values in a HashMap.
  • 4. Null Elements: In a HashSet we can store a single null value. In a HashMap we can store single null key, but any number of null values.
  • 5. Element Type: A HashSet contains only values of objects as its elements. Whereas a HashMap contains entries(key value pairs).
  • 6. Iteration: By using an Iterator we can iterate a HashSet. But a HashMap has to be converted into Set for iteration.

37.What are the similarities between a HashSet and a HashMap in Java?
As the name suggests, HashSet and HashMap are Hashing based collections. Similarities between HashSet and HashMap are:

  • 1. Thread Safety: Both HashMap and HashSet are not synchronized collections. Therefore they are not good for thread-safe operations. To make these thread-safe we need to explicitly use synchronized versions.
  • 2. Order of Elements: None of these classes guarantee the order of elements. These are unordered collections.
  • 3. Internal Implementation: A HashMap backs up a HashSet internally. So HashSet uses a HashMap for performing its operations.
  • 4. Performance: Both of these collections provide constant time performance for basic operations such as insertion and removal of elements.

38. What is the reason for overriding equals() method?
The equals() method in Object class is used to check whether two objects are same or not. If we want a custom implementation we can override this method.
For example, a Person class has first name, last name and age. If we want two Person objects to be equal based on name and age, then we can override equals() method to compare the first name, last name and age of Person objects.
Generally in HashMap implementation, if we want to use an object as key, then we override equals() method.

39.How can we synchronize the elements of a List, a Set or a Map?
Sometimes we need to make collections Thread-safe for use in Multi-threading environment. In Java, Collections class provides useful static methods to make a List, Set or Map as synchronized collections. Some of these methods are:

Returns a synchronized (thread-safe) collection backed by the specified collection.

Returns a synchronized (thread-safe) list backed by the specified list.

Returns a synchronized (thread-safe) map backed by the specified map.

Returns a synchronized (thread-safe) set backed by the specified set.

Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.

Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.

40. What is Hash Collision? How Java handles hash-collision in HashMap?
In a Hashing scenario, at times two different objects may have same HashCode but they may not be equal. Therefore, Java will face issue while storing the two different objects with same HashCode in
a HashMap. This kind of situation is Hash Collision. There are different techniques of resolving or avoiding Hash Collision. But in HashMap, Java simply replaces the Object at old Key with new Object in case of Hash Collision.

41. What are the Hash Collision resolution techniques?
To resolve a Hash Collision we can use one of the following techniques:

  • Separate Chaining with Linked List
  • Separate Chaining with List Head Cells
  • Open Addressing with Coalesced Hashing
  • Open Addressing with Cuckoo Hashing
  • Hopscotch Hashing
  • Robinhood Hashing

42.What is the difference between Queue and Stack data structures?
Queue is a FIFO data structure. FIFO stands for First In First Out. It means the element added first will be removed first from the queue. A real world example of Queue is a line for buying tickets at a station. The person entering first in the Queue is served first. Stack is a LIFO data structure. LIFO stands for Last In First Out. The element that is added last is removed first from the collection. In a Stack elements are added or removed from the top of stack. A real world example of Stack is back button in browser. We can go back one by one only and it works in the reverse order of adding webpages to history .

43.What is an Iterator in Java?
Iterator is an interface in Java to access the elements in a collection. It is in java.util package. It provides methods to iterate over a Collection class in Java.
Iterator interface in Java is based on Iterator design pattern. By using an Iterator one can traverse a container of objects and can also access the objects in the container. A container of objects is a Collection class in Java.

44. What is the difference between Iterator and Enumeration in Java?
Main differences between Iterator and Enumeration in Java are:

  • 1. Version: Enumeration interface is in Java since JDK 1.0. Iterator interface was introduced in Java 1.2.
  • 2. remove() method: The main difference between Enumeration and Iterator interface is remove() method. Enumeration can just traverse a Collection object. If we use Enumeration, we cannot do any modifications to a Collection while traversing the collection. Iterator interface provides remove() method to remove an element while traversing the Collection. There is not remove() method in Enumeration interface.
  • 3. Method names: Names of methods in Iterator interface are hasNext(), next(), remove(). Names of methods in Enumeration interface are hasMoreElements(), nextElement().
  • 4. Legacy Interface: Enumeration is considered as a legacy interface. It is used to traverse legacy classes like Vector, Stack and HashTable. Iterator is a newer interface that is used to traverse almost all of the classes in Java Collections framework.
  • 5. Fail-fast vs. Fail-safe: Iterator is based on fail-fast principle. It throws ConcurrentModificationException if a collection is modified during iteration over that collection. An Enumeration is based on fail-safe principle. It doesn’t throw any exception if a collection is modified during traversal.
  • 6. Safety: Since Iterator is fail-fast and does not allow modification of a collection by other threads, it is considered safer than Enumeration.

45. What is the design pattern used in the implementation of Enumeration in Java?
Enumeration is based on Iterator design pattern. Iterator design pattern provides a common interface with methods to traverse the collection of objects. It hides the underlying implementation details of the collection.

46.Which methods do we need to override to use an object as key in a HashMap?
If we want to use an object as a key in a HashMap in Java, then we have to make sure that it has the implementation of equals() and hashCode() methods.

47.How will you reverse a List in Java?
In Collections class, Java provides a method reverse(List list) that can be used to reverse a List. E.g.

48.How will you convert an array of String objects into a List?
Java provides Arrays class in java.util package. Arrays class has a method asList() that accepts an Array as input and returns a List as output.

49.What is the difference between peek(), poll() and remove() methods of Queue interface in java?
In a Java Queue, poll() and remove() methods can be used for removing the head object of Queue. The main difference arises in the case when Queue is empty().
If Queue is empty then poll() method returns null value. If Queue is empty then remove() method throws NoSuchElementException.
In a Java Queue, peek() method retrieves the head of Queue but it does not remove it. If queue is empty then peek() method returns null value.

50. What is the difference between Array and ArrayList in Java?
The main differences between Array and ArrayList in Java are:

  • 1. Size: Array in Java is fixed in size. We cannot change the size of array after creating it. ArrayList is dynamic in size. When we add elements to an ArrayList, its capacity increases automatically.
  • 2. Performance: In Java Array and ArrayList give different performance for different operations.
  • 3. add() or get(): Adding an element to or retrieving an element from an array or ArrayList object has similar performance. These are constant time operations.
  • 4. resize(): Automatic resize of ArrayList slows down the performance. ArrayList is internally backed by an Array. In resize() a temporary array is used to copy elements from old array to new array.
  • 5. Primitives: Array can contain both primitive data types as well as objects. But ArrayList cannot contain primitive data types. It contains only objects.
  • 6. Iterator: In an ArrayList we use an Iterator object to traverse the elements. We use for loop for iterating elements in an array.
  • 7. Type Safety: Java helps in ensuring Type Safety of elements in an ArrayList by using Generics. An Array cancontain objects of same type of class. If we try to store a different data type object in an Array then it throws ArrayStoreException.
  • 8. Length: Size of ArrayList can be obtained by using size() method. Every array object has length variable that is same as the length/size of the array.
  • 9. Adding elements: In an ArrayList we can use add() method to add objects. In an Array assignment operator is used for adding elements.
  • 10. Multi-dimension: An Array can be multi-dimensional. An ArrayList is always of single dimension.

51.How will you insert, delete and retrieve elements from a HashMap collection in Java?
We use following methods to insert, delete and retrieve elements in a HashMap.

  • 1. Retrieve: We use get() method to retrieve elements from a HashMap.

  • 2. Insert: We use put() method to insert a key value pair in a HashMap.

  • 3. Delete: We use remove() method to delete key-value pair from the HashMap.

52.What are the main differences between HashMap and ConcurrentHashMap in Java?
Main differences between HashMap and ConcurrentHashMap are:

  • 1. Synchronization: A HashMap is not synchronized. But a ConcurrentHashMap is a synchronized object.
  • 2. Null Key: A HashMap can have one null key and any number of null values. A ConcurrentHashMap cannot have null keys or null values.
  • 3. Multi-threading: A ConcurrentHashMap works well in a multi-threading environment.

53.What is the increasing order of performance for following collection classes in Java?
The increasing order of performance is:

  • Hashtable
  • Collections.SynchronizedMap
  • ConcurrentHashMap
  • HashMap

Hashtable has the worst performance and HashMap has the best performance.

54. Why does Map interface not extend Collection interface in Java?
A Map is a collection objects. But Map interface is not compatible with Collection interface in Java.
A Map requires key as well as a value. So it requires two parameters to add an element to a HashMap.
But Collection interface provides add(Object o) method with only one parameter. Map collection has to provide methods like valueSet, keySet etc.
These methods are specific to Map collection. Where as methods in Collection interface can be reused by a List, Set, Queue etc.

55.What are the different ways to iterate elements of a list in Java?
There are mainly two ways to iterate the elements of list in Java:

  • 1. Iterator: We can get an Iterator for list and use it to iterate the objects of the list.
  • 2. For-each loop: We can use for-each loop to traverse all the elements of a list.

56. What is CopyOnWriteArrayList? How it is different from ArrayList in Java?
CopyOnWriteArrayList was introduced in Java 5 version. It is a thread-safe collection. It is similar to an  ArrayList.
In CopyOnWriteArrayList, all mutative operations (add, set etc.) are implemented by making a fresh copy of the underlying array.
Iterator of CopyOnWriteArrayList is guaranteed to not throw ConcurrentModificationException. But Iterator also does not reflect any additions, removals that happened to list after the Iterator was created.
All elements including null are permitted in CopyOnWriteArrayList.

Continue reading 100 Java Collection Interview Questions and Answers (Part 3)




Leave a Comment


Please share it if you found this useful
Hide Buttons