Top 60 Java Collections Interview Questions for 2021


Collection Interview JavaViews 1991

Below are the most frequently asked Java Collections interview questions with answers. This will help you to crack collections interview questions in 2021.

Table of Contents

1. What is a framework?

A framework is a predefined architecture that contains a set of several classes and interfaces which can be used directly without any modification.

2. What is a Collection framework?

In Java, a collection is a single entity that represents a group of objects and a framework is a defined architecture that contains interfaces and classes. Hence, the Java Collection framework is an architecture that defines a set of interfaces, classes, and algorithms. This framework was available from JDK 1.2. It can also perform operations like search, insert, sort, delete, manipulate, etc.

3. What is a Collections class?

Collections is a class in Java that is part of java.util package and contains various static methods that we can use to perform operations on the Collections. It also contains methods for various algorithms like sorting, binary search, etc.

4. What are the differences between an Array and Collections?

ArrayCollection
It is fixed size and cannot change the size in runtimeThe size can be dynamically changed and is not fixed.
It can store only same type of dataIt can store combination of data type values
It does not have built-in methods like sorting or searchingIt has built-in methods for sorting and searching
Performance is fastPerformance is slow
Memory efficiency is lessMemory efficiency is more
It is not implemented based on any data structureEvery class in Collection is implemented based on some data structure

5. What are the various interfaces present in the Collection framework?

Collection interface: This is the root interface of the Collection framework hierarchy. The other interfaces which are present in the Collection framework are Map and Iterator interfaces. These interfaces further have subinterfaces since there is no direct implementation for the Collection interface.

The Collection interfaces contain List, Set, and Queue interfaces.

List interface: This is an ordered collection of elements that allows storing duplicate values.

Set interface: This is an unordered collection of elements and does not allow duplicate values.

Queue interface: It implements the queue data structure and follows the FIFO(First-In-First-Out) concept.

Deque interface: This is a double-ended queue that implements both stack and queue and hence supports both FIFO and LIFO.

Map interface: It stores data in the form of key-value pairs and we can store only unique keys.

6. What are the differences between ArrayList and Vector?

ArrayListVector
ArrayList is not synchronizedVector is synchronized
It is not a legacy classIt is a legacy class
It can increase its size by 50% of the array sizeIt can increase its size by doubling
It is not thread-safeIt is thread-safe
Uses only Iterator for traversingUses both Enumeration and Iterator for traversing
ArrayList performance is fasterVector performance is comparatively slower

7. What are the differences between ArrayList and LinkedList?

ArrayListLinkedList
Uses dynamic array to store elementsUses Double LinkedList to store elements
Performance is slowerPerformance is faster
It can be used to implement only ListIt can be used to implement List and Queue
Provides random accessDoes not provide random access
Occupies less memory since it stores only objectOccupies more memory since it stores both object and reference of the object
get(int index) gives performance of O(1)get(int index) gives performance of O(n)
Removal operation performance in worst case is O(n) and best case is O(1)Removal operation gives performance of O(1)
Add method gives performance of O(n) in worst caseAdd method gives performance of O(1)

8. What are the differences between Iterator and ListIterator?

IteratorListIterator
It is a universal iteratorIt is not a universal iterator
It can be used for any type of CollectionIt can be used only for List implementation classes
Supports only read and delete operationSupports add, update, read and delete operations.
Can be used only for forward navigationCan be used for forward and reverse direction navigation
It is not a bidirectional iteratorIt is a bidirectional iterator
We use the iterator() methodWe use the listiterator() method.
We cannot specify the index for iterationWe can specify the index for iteration

9. What are the differences between Iterator and Enumeration?

EnumerationIterator
Available from JDK 1.0Available from JDK 1.2
It is not a universal iteratorIt is a universal iterator
It can be used to iterate only legacy collections like Vector, hashtableIt can be used to iterate any Collections
Supports only read operationSupports both read and delete operation
It has lengthy method names
Eg: hasMoreElements()
It has short method names
Eg: hasNext()

10. What are the differences between List and Set?

ListSet
It can store duplicate elementsIt can store only unique elements
It is an ordered collectionIt is an unordered collection
It has a single legacy class which is VectorIt does not have any legacy class
It can store any number of null valuesIt can store only a single null value

11. What are the differences between HashSet and TreeSet?

TreeSetHashSet
Maintains ascending orderDoes not maintain any order
Computation is slowerComputation is faster
Time cost is log(n)Time cost is constant

12. What are the differences between Set and Map?

SetMap
Set stores only valuesMap stores key and values
Set can contain unique valuesMap can contain unique keys and duplicate values
It can hold single null valueIt can hold single null key and multiple null values

13. What are the differences between HashSet and HashMap?

HashSetHashMap
It implements the Set interfaceIt implements the Map interface
It stores only valuesIt stores data in the form of key-value pair
It cannot have duplicate valuesIt can contain duplicate values with unique keys
It can have only a single null valueIt can hold a single null key with multiple null values

14. What are the differences between HashMap and TreeMap?

TreeMapHashMap
Maintains ascending orderDoes not maintain any order
Cannot contain null keyCan contain one null key
It is a tree structure based implementationIt is a hashtable based implementation
It does not allow null valuesIt allows multiple null values
Sorting is slowerSorting is faster
Uses red-black tree data structureIt uses a hashtable data structure

15. What are the differences between HashMap and HashTable?

HashMapHashtable
It is not synchronizedIt is synchronized
It is not thread safe and cannot be shared between threadsIt is thread safe and can be shared between threads
Allows one null key and multiple null valuesDoes not allow null key and null value
Introduced in JDK 1.2It is a legacy class
We use Iterator to traverse through HashmapWe use Iterator or Enumeration to traverse through Hashtable
Inherits AbstractMap classInherits Dictionary class
Computation is fastComputation is slow

16. What are the differences between Collection and Collections?

CollectionsCollection
This is a classThis is an interface
Provides methods for sorting, searching and synchronizationProvides data structure for queue, list, set
Provides static methods for various operations on CollectionProvides methods to support data structure

17. What are the differences between Comparator and Comparable?

ComparatorComparable
Provides multiple sorts of sequencesProvides single sort of sequences
It has an in-built method named compare()It has an in-built method names compareTo()
It is part of the java.util packageIt is part of the java.lang package
The actual class is not modifiedThe actual class is modifying on implementation

18. What is BlockingQueue?

BlockingQueue is an interface that provides concurrency in operations like insert and delete elements. This means it inserts an element by waiting till the queue has available space and deletes an element by waiting till the queue is non-empty.

19. What is the advantage of the Properties file?

A property file is a file that helps in changing or updating the file without the need to recompile the java class. It helps in managing data and is useful when there is frequent update to file data.

20. What is the hashCode() method?

The hashCode() method is used in the hashing technique that returns an integer number that is used to store key-value pairs. It is used in Collections like HashSet, HashMap, etc. It returns the same integer value when both keys are identical. In case both objects are different, then it returns a different integer value for both the objects.

21. Why do we override the equals() method?

The equals method checks if two objects are equal. This is present in the Object class and we need to override it in order to check the equality.

22. How to synchronize List, Set, and Map elements?

We can synchronize the elements using the synchronized method.

23. What are the advantages of generic collections?

  • It does not require typecasting
  • It checks during compile-time and is type-safe.
  • Also checks for bugs during compile time itself

24. What is hash-collision and how is it handled?

Hash collision is the process when two different keys produce the same integer value or hash value. We can avoid hash collision by using the below 2 techniques:

  • Separate chaining
  • Open addressing

25. What is the default size of the load factor in hashing?

The default size of the load factor is 0.75.

26. What is fail-fast?

The fail-fast is a condition in which the iterator throws the ConcurrentModificationException when there is a structural modification.

27. What is the difference between Array and ArrayList?

ArrayArrayList
It is of fixed-sizeIt is of dynamic size
It is staticIt is dynamic
It can store primitive values and objectsIt can store only objects

28. What is the difference between the length of an array and the size of ArrayList?

We can retrieve the length of an array using the length property for an array. But the ArrayList does not support this. Hence it uses the size() method to find the size of the ArrayList. Both return the number of elements in an array or ArrayList.

29. How to convert an array to ArrayList and vice versa?

We can use the asList() method to convert an array to ArrayList and we can use the toArray() method to convert the ArrayList to an array.

30. How to make Java ArrayList as read-only?

When an ArrayList is read-only, we can only read the values and cannot modify or update it. We can do this by using the Collections.unmodifiableCollection() method.

31. How can we remove duplicates from ArrayList?

We can remove duplicates from ArrayList by using the HashSet or LinkedHashSet.

32. What are the new features of Collections in Java 8?

  • Java Stream API support
  • Many new methods for improvements like forEachRemaining() in Iterator, replaceAll(), compute() and merge() methods in Map.
  • Extension of Iterable interface with forEach() default method.

33. Why Map interface does not extend the Collection interface?

A Map interface represents data in the form of key-value pairs while the Collections do not support this. Hence a Map interface cannot be considered as a Collection and hence not part of the Collection framework.

34. What is an Iterator?

An Iterator is an interface that has an iterator() method that helps us to iterate or traverse through all the elements in the Collection.

35. What are the different ways to iterate through a list?

We can iterate through a list in two different ways:

  • Using the for-each loop
  • Using iterator

36. What are the different Collection views provided by the Map interface?

The Map interface provides the below Collection views:

  • keySet(): This method returns a Set view of the elements.
  • values(): This method returns a Collection of values in the map.
  • entrySet(): This method returns a Set view of the key-value pair mapping present in the map.

37. Which Collection class provides random access to elements?

ArrayList, HashMap, TreeMap, HashTable, and Vector classes.

38. What is EnumSet?

EnumSet stores Enumeration data types and implements the Set interface. All the elements should belong to the single Enum type and does not allow to store null values.

39. Which Collection classes are thread-safe?

Vector, Hashtable, Properties, and Stack classes.

40. How can we sort a list of Objects?

We can sort a list of Objects using the Arrays.sort() or Collections.sort()

41. Why Collection does not extend the Cloneable and Serializable interfaces?

The Collection interface contains elements that are nothing but a group of objects. The order of the elements is based on the implementation of the Collection interface. Hence it is not required to extend the Cloneable and Serializable interface.

42. How to reverse a list?

We can use the reverse() method to reverse the elements in the list.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

public class ArrayListReverse {

  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<Integer>();
    al.add(30);
    al.add(10);
    al.add(50);
    al.add(40);
    al.add(20);
    
    System.out.println("Elements in the ArrayList");
    System.out.println(al);
    
    System.out.println("

Sort Elements

 in descending order:");
    Collections.reverse(al);
    System.out.println(al);

  }

}
Elements in the ArrayList
[30, 10, 50, 40, 20]
Sort Elements in descending order:
[20, 40, 50, 10, 30]

43. How many types of LinkedList does Java support?

LinkedList in Java supports two types: Single LinkedList, Doubly LinkedList

44. What is a Set and what are the various implementations?

A Set is unordered collection of elements which means it does not maintain any insertion order and cannot store any duplicate values.

The HashSet, LinkedHashSet, and TreeSet are the classes that implement the Set interface.

45. What is an emptySet()?

An emptySet() returns empty immutable set whenever we try to remove null elements. This set is serializable.

46. What is a Vector?

A vector is similar to array but was part of the legacy framework and has separate methods apart from the Collections framework.

47. What is a dictionary class?

A dictionary class that can store key-value pairs.

48. What is an UnsupportedOperationException?

The UnsupportedOperationException is thrown when the method is not supported by the Collection type.

49. What is a peek() method in Queue?

The peek() method returns the head element but does not remove it. If the queue is empty then it returns null.

50. What are the best practices in the Collection framework?

  • Select the correct type of collection based on the requirement
  • Avoid rehashing or resizing
  • Use more interfaces
  • Use generics for type-safety
  • Enhance code reusability by using the Collection utility class
  • Use immutable classes

51. What are the different types of queue?

  • PriorityQueue
  • Double-ended queue(deque)
  • Circular queue

52. What are the differences between stack and queue?

StackQueue
Follows LIFO conceptFollows FIFO concept
Performs insertion or deletion operation through one endPerforms insertion through one end and deletion through the other end
Uses a single pointerUses double pointers
There is no variant typesThere are variants like PriorityQueue, CircularQueue, Double-ended Queue

53. What are the differences between array and stack?

ArrayStack
Stores elements of same data typeStores elements of different data types
We can use random access operation to remove or add elementsWe can use LIFO concept to add or remove elements
Identifies the elements based on the indexUsed for push and pop operations

54. What are the advantages of a stack?

  • Uses LIFO concept to manage the data
  • Automatically cleans up the object
  • Memory allocation and deallocation management is easier
  • Uses stack when the variable is not used outside the function
  • Does not easily get corrupted

55. What is a Big-O notation?

The Big-O notation is to calculate the performance of the algorithm based on the number of elements. We can use this to compare and check which collection type is adaptable to implement.

For example, the getIndex(index i) method of the ArrayList performs a constant time and does not depend on the number of elements. Hence the Big-O notation is O(1).

56. What is a LinkedList?

The LinkedList is a class that implements both deque and List using the double linked list. Each element is a node that has 2 parts, one stores the value, and the other stores the address reference of the previous and next nodes.

57. What is Map.entry in Map?

Map.entry is an interface that supports working with a map entry. It returns a view of the collection. We can use the entrySet() method to retrieve the set view of the map that has the key-value pairs. It also has separate methods like getKey() to retrieve the key and getValue() to retrieve the value.

58. What are the different methods to remove elements from an ArrayList?

  • clear(): Removes all the elements and empties the ArrayList
  • remove(int index): Removes the element at the specified index
  • remove(Object o): Removes the specified element
  • removeAll(): Removes all the elements in the list
  • removeIf(Predicate filter): Removes the elements that satisfy the predicate

59. How to join multiple ArrayList?

We can join or merge the elements of different ArrayList using the addAll(Collection c) method.

ArrayList<String> al = new ArrayList<String>();
ArrayList<String> arr = new ArrayList<String>();
al.addAll(arr);

60. What is a diamond operator?

The diamond operator supports to retrieve the argument types of the generic class. It is represented as <> and can replace the parameterized constructor with empty parameter sets.

Translate ยป