Open In App

Java Collections & Generics Interview Questions

Last Updated : 17 Dec, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

Java Collections Framework (JCF) is a standard library that provides data structures and algorithms to store, retrieve and manipulate data efficiently. It is one of the most important topics in Java interviews.

This covers the most important Collection Frameworks & Generics interview questions in Java, explained in a clear, concise manner with examples.

1. What is the Collection Framework in Java?

A Collection is a group of objects in Java. The collection framework is a set of interfaces and classes in Java that are used to represent and manipulate collections of objects in a variety of ways. The collection framework contains classes (ArrayList, Vector, LinkedList, PriorityQueue, TreeSet) and multiple interfaces (Set, List, Queue, Deque) where every interface is used to store a specific type of data.

2. What is the difference between Collection and Collections?

1. Collection:

  • It is an interface in the java.util package.
  • It represents a group of objects (elements).
  • Used as a parent interface for List, Set, and Queue.

2. Collections:

  • It is a utility class in the java.util package.
  • Provides static methods like sort(), reverse(), shuffle().
  • Used to perform operations on Collection objects.

3. Explain various interfaces used in the Collection framework.

Collection-Framework

The collection framework implements

  1. Collection Interface
  2. List Interface
  3. Set Interface
  4. Queue Interface
  5. Deque Interface
  6. Map Interface

4. What is the List interface in Java?

The List interface in Java extends the Collection interface and is part of the java.util package. It is used to store ordered collections where duplicates are allowed and elements can be accessed by their index.

  • Maintains insertion order
  • Allows duplicate elements
  • Supports null elements (implementation dependent)
  • Supports bidirectional traversal using ListIterator

Syntax:

public interface List<E> extends Collection<E> { }

5. What are the implementations classes of list interface

The List interface in Java is implemented by the following main classes:

list
  • ArrayList: It is implemented using resizable array, offers fast random access but slower insert/delete.
  • LinkedList: It is implemented using Doubly-linked list, efficient for frequent insertions and deletions.
  • Vector: It is implemented using Legacy synchronized dynamic array, thread-safe but slower.
  • Stack: It is implemented using a LIFO (Last-In-First-Out) subclass of Vector for stack operations.

6. How can you synchronize an ArrayList in Java?

An ArrayList can be synchronized using two methods mentioned below:

1. Using Collections.synchronizedList(): Wrap the ArrayList inside a synchronized list.

Java
List<String> list = new ArrayList<>();

List<String> syncList = Collections.synchronizedList(list);

synchronized (syncList) {
    for (String s : syncList) {
        System.out.println(s);
    }
}

2. Using CopyOnWriteArrayList: Instead of synchronizing manually, use a thread-safe collection from java.util.concurrent.

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

7. Why do we need a synchronized ArrayList when we have Vectors (which are synchronized) in Java?

Vector is always synchronized, which makes it slow. ArrayList can be synchronized only when needed, giving better performance and flexibility.

8. Why can’t we create a generic array?

Generic arrays can't be created because an array carries type information of its elements at runtime because of which during runtime it throw 'ArrayStoreException' if the elements' type is not similar. Since generics type information gets erased at compile time by Type Erasure, the array store check would have been passed where it should have failed.

9. How are elements stored in memory for arrays and ArrayLists in Java?

Array: In arrays, elements are stored in contiguous memory locations, making access very fast using an index.

ArrayList: In ArrayList, elements are stored inside a resizable array, which grows automatically; although memory is still contiguous, resizing may involve creating a new larger array and copying elements.

10. How do you convert an ArrayList to an Array and an Array to an ArrayList in Java?

1. Convert Array to ArrayList: There are multiple methods to convert Array into ArrayList

Convert-Array-into-ArrayList-768

Programmers can convert an Array to ArrayList using asList() method of the Arrays class. It is a static method of the Arrays class that accepts the List object.

Syntax:

Arrays.asList(item)

Example: Java program to demonstrate conversion of Array to ArrayList of fixed-size.

Java
import java.util.*;
// Driver Class
class GFG {
    // Main Function
    public static void main(String[] args)
    {
        String[] temp = { "Abc", "Def", "Ghi", "Jkl" };
        // Conversion of array to ArrayList using Arrays.asList
        List conv = Arrays.asList(temp);
        System.out.println(conv);
    }
}

Output
[Abc, Def, Ghi, Jkl]

2. Convert ArrayList to Array

Convert-ArrayList-to-Array-768

Syntax:

List_object.toArray(new String[List_object.size()])

Example: Java programmers can convert ArrayList to

Java
import java.util.List;
import java.util.ArrayList;

// Driver Class
class GFG {
    // Main Function
    public static void main(String[] args) {
        // List declared
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(2);
        arr.add(1);
        
        // Conversion
        Object[] objects = arr.toArray();
        
        // Printing array of objects
        for (Object obj : objects)
            System.out.print(obj + " ");
    }
}

Output
1 2 3 2 1 

11. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

An ArrayList stores elements in an internal array. When the array is full, it automatically creates a larger array (about 1.5× the old size) and copies existing elements, allowing dynamic growth.

12. What is a Vector in Java?

A Vector in Java is a dynamic array that can grow or shrink automatically when elements are added or removed. It is part of the java.util package. Vector is very similar to ArrayList, but the key difference is: Vector is synchronized (thread-safe), while ArrayList is not.

Java
import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<>();
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Apple"); // duplicate allowed
        System.out.println(vector); // Output: [Apple, Banana, Apple]
    }
}

Output
[Apple, Banana, Apple]

13. How to make Java ArrayList Read-Only?

An ArrayList can be made ready only using the method provided by Collections using the Collections.unmodifiableList() method. 

Syntax:

array_readonly = Collections.unmodifiableList(ArrayList);

Example:

Java
        import java.util.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        try {
            // creating object of ArrayList
            ArrayList<Character> temp = new ArrayList<>();
            // populate the list
            temp.add('X');
            temp.add('Y');
            temp.add('Z');
            // printing the list
            System.out.println("Initial list: " + temp);
            
            // getting readonly list using unmodifiableList() method
            List<Character> new_array = Collections.unmodifiableList(temp);
            
            // printing the list
            System.out.println("ReadOnly ArrayList: " + new_array);
            
            // Attempting to add element to new Collection
            System.out.println("\nAttempting to add element to the ReadOnly ArrayList");
            new_array.add('A');
        } catch (UnsupportedOperationException e) {
            System.out.println("Exception is thrown : " + e);
        }
    }
}

Output
Initial list: [X, Y, Z]
ReadOnly ArrayList: [X, Y, Z]

Attempting to add element to the ReadOnly ArrayList
Exception is thrown : java.lang.UnsupportedOperationException

14. Explain the LinkedList class.

The LinkedList class in Java is a collection class that uses a doubly linked list to store elements. It inherits the AbstractSequentialList class and implements the List and Deque interfaces. Properties of the LinkedList Class are mentioned below:

  • LinkedList classes are non-synchronized.
  • Maintains insertion order.
  • It can be used as a list, stack or queue.

Syntax:

LinkedList<class> list_name=new LinkedList<class>();

Example:

Java
import java.util.LinkedList;

public class LinkedListExample{
    
    public static void main(String[] args){
        
        LinkedList<String> list = new LinkedList<>();
        list.add("Apple");
        list.add("Banana");
        list.addFirst("Mango");  // Adds at the beginning
        list.addLast("Orange");  // Adds at the end

        System.out.println(list); // Output: [Mango, Apple, Banana, Orange]
    }
}

Output
[Mango, Apple, Banana, Orange]

15. What is the Stack class in Java and what are the various methods provided by it?

A Stack class in Java is a LIFO data structure that implements the Last In First Out data structure. It is derived from a Vector class but has functions specific to stacks. The Stack class in java provides the following methods:

  • peek(): returns the top item from the stack without removing it
  • empty(): returns true if the stack is empty and false otherwise
  • push(): pushes an item onto the top of the stack
  • pop(): removes and returns the top item from the stack
  • search(): returns the 1, based position of the object from the top of the stack. If the object is not in the stack, it returns -1

16. What is Set Interface?

In Java, the Set interface is a part of the Java Collection Framework, located in the java.util package. It represents a collection of unique elements, meaning it does not allow duplicate values.

  • The set interface does not allow duplicate elements.
  • It can contain at most one null value except TreeSet implementation which does not allow null.
  • The set interface provides efficient search, insertion, and deletion operations.

Example:

Java
import java.util.HashSet;
import java.util.Set;

public class Geeks {
    
  	public static void main(String args[]) 
    {
        // Create a Set using HashSet
        Set<String> s = new HashSet<>();

        // Displaying the Set
        System.out.println("Set Elements: " + s);
    }
}

Output
Set Elements: []

17. What are the implementation classes of the set interface?

set
  • HashSet: A set that stores unique elements without any specific order, using a hash table and allows one null element.
  • EnumSet : A high-performance set designed specifically for enum types, where all elements must belong to the same enum.
  • LinkedHashSet: A set that maintains the order of insertion while storing unique elements.
  • TreeSet: A set that stores unique elements in sorted order, either by natural ordering or a specified comparator.

18. What is the HashSet class in Java and how does it store elements?

HashSet is a class in java.util that implements the Set interface. It stores unique elements only (no duplicates allowed) and does not maintain any order of elements.

How HashSet Stores Elements:

  • Internally, HashSet uses a HashMap to store elements.
  • Each element is stored as a key in the HashMap, and a dummy object is used as the value.
  • Elements are stored based on their hashCode().
  • Collision handling is done using linked lists or balanced trees (Java 8+).

Example:

Java
import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args)
    {
        HashSet<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Apple"); // duplicate ignored

        System.out.println(set); 
    }
}

Output
[Apple, Banana]

19. What is LinkedHashSet in Java Collections Framework?

The LinkedHashSet is an ordered version of Hashset maintained by a doubly-linked List across all the elements. It is very helpful when iteration order is needed. During Iteration in LinkedHashSet, elements are returned in the same order they are inserted.

Syntax: 

LinkedHashSet<E> hs = new LinkedHashSet<E>();

Example:

Java
import java.io.*;
import java.util.*;

// Driver Class
class GFG {
    // Main Function
    public static void main(String[] args) {
        // LinkedHashSet declared
        LinkedHashSet<Integer> hs = new LinkedHashSet<Integer>();
        // Add elements in HashSet
        hs.add(1);
        hs.add(2);
        hs.add(5);
        hs.add(3);
        // Print values
        System.out.println("Values:" + hs);
    }
}

Output
Values:[1, 2, 5, 3]

20. What is a queue interface in Java?

The Queue interface is part of the java.util package. It extends the Collection interface.

  • Elements are processed in the order determined by the queue implementation (First In First Out or FIFO for LinkedList, priority order for PriorityQueue).
  • Elements cannot be accessed directly by index.
  • A queue can store duplicate elements.

Example:

Java
import java.util.PriorityQueue;
import java.util.Queue;

public class Geeks{

    public static void main(String[] args){
        
        // Create a PriorityQueue of Integers
        Queue<Integer> pq = new PriorityQueue<>();
        
        // Adding elements to the PriorityQueue
        pq.add(50);
        pq.add(20);
        pq.add(40);
        pq.add(10);
        pq.add(30);
        
        // Display the PriorityQueue elements
        System.out.println("PriorityQueue elements: " + pq);
    }
}

Output
PriorityQueue elements: [10, 20, 40, 50, 30]

21. What are the implementation classes of the queue interface?

Implementation classes of queue interface:

  • LinkedListA FIFO queue that allows null elements and implements both Queue and Deque interfaces.
  • ArrayDeque: A resizable array-based queue that is faster than LinkedList and does not allow nulls.
  • PriorityQueue: A queue where elements are processed according to their priority instead of insertion order.
  • ConcurrentLinkedQueue: A thread-safe, non-blocking queue suitable for concurrent environments.
  • BlockingQueue: A thread-safe queue that supports blocking operations for producer-consumer scenarios.

22. What is a priority queue in Java?

Priority-Queue-768

A priority queue is an abstract data type similar to a regular queue or stack data structure. Elements stored in elements are depending upon the priority defined from low to high. The PriorityQueue is based on the priority heap.

Syntax:

Java
import java.util.*;

class PriorityQueueDemo {
    // Main Method
    public static void main(String args[]) {
        // Creating empty priority queue
        PriorityQueue<Integer> var1 = new PriorityQueue<Integer>();
        // Adding items to the pQueue using add()
        var1.add(10);
        var1.add(20);
        var1.add(15);
        // Printing the top element of PriorityQueue
        System.out.println(var1.peek());
    }
}

Output
10

23. What is BlockingQueue?

BlockingQueue-768

A blocking queue is a Queue that supports the operations that wait for the queue to become non-empty while retrieving and removing the element and wait for space to become available in the queue while adding the element.

Syntax:

public interface BlockingQueue<E> extends Queue<E>

Parameters: E is the type of elements stored in the Collection

24. What is a Map interface in Java?

Map-Interface-in-Java-660

The map interface is present in the Java collection and can be used with Java.util package. A map interface is used for mapping values in the form of a key-value form. The map contains all unique keys. Also, it provides methods associated with it like containsKey(), contains value (), etc. 

There are multiple types of maps in the map interface as mentioned below:

  • SortedMap
  • TreeMap
  • HashMap
  • LinkedHashMap

25. What is TreeMap? Explain internal working.

TreeMap is a sorted map in Java that stores key-value pairs in ascending key order. Internally, it uses a Red-Black Tree, where keys are placed based on their natural order or a custom Comparator, and the tree self-balances to ensure O(log n) time for get, put, and remove operations.

Example:

Java
import java.util.TreeMap;

public class TreeMapExample{
    
    public static void main(String[] args){
        
        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(3, "Apple");
        map.put(1, "Banana");
        map.put(2, "Mango");

        System.out.println(
            map); // Output: {1=Banana, 2=Mango, 3=Apple}
    }
}

Output
{1=Banana, 2=Mango, 3=Apple}

26. What is EnumSet?

EnumSet is a specialized implementation of the Set interface for use with enumeration type. A few features of EnumSet are:

  • It is non-synchronized.
  • Faster than HashSet.
  • All of the elements in an EnumSet must come from a single enumeration type.
  • It doesn't allow null Objects and throws NullPointerException for exceptions.
  • It uses a fail-safe iterator.

Syntax:

public abstract class EnumSet<E extends Enum<E>>

Parameter: E specifies the elements.

27. What is a HashMap in Java?

A HashMap is a part of the Java Collections Framework that implements the Map interface. It stores data in key-value pairs, where each key is unique, and each key maps to exactly one value.

Java
import java.util.HashMap;

public class GFG{
    
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        
        // Adding key-value pairs
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Mango");
        
        // Accessing a value
        System.out.println(map.get(2)); // Output: Banana
        
        // Iterating over HashMap
        for (Integer key : map.keySet()) {
            System.out.println(key + " => " + map.get(key));
        }
    }
}

Output
Banana
1 => Apple
2 => Banana
3 => Mango

28. What is ConcurrentHashMap in Java?

ConcurrentHashMap is a thread-safe implementation of the Map interface in Java. Unlike HashMap, it allows concurrent read and write operations without locking the entire map, making it highly efficient in multithreaded environments.

Example:

Java
import java.util.concurrent.ConcurrentHashMap;

public class GFG{
    
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap
        ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();

        // Adding key-value pairs
        map.put(1, "Amit");
        map.put(2, "Rahul");
        map.put(3, "Sneha");

        // Accessing a value
        System.out.println(map.get(2)); // Output: Rahul

        // Iterating over ConcurrentHashMap
        map.forEach((key, value) -> {
            System.out.println(key + " => " + value);
        });

        // Removing a value
        map.remove(3);
    }
}

Output
Rahul
1 => Amit
2 => Rahul
3 => Sneha

29. Can you use any class as a Map key?

Yes, any class can be used as a Map key if it follows these rules:

  • The class must override both equals() and hashCode() methods properly.
  • Keys should be immutable for reliable behavior.
  • null cannot be used as a key in HashMap (before Java 8 only one null key was allowed, not in ConcurrentHashMap).

30. What is a cursor in Java Collections

A cursor is an object used to traverse elements of a collection. Java provides three types of cursors:

  • Enumeration: legacy, can read elements only, used with Vector and Hashtable.
  • Iterator: can read and remove elements, works with all collection classes.
  • ListIterator: extends Iterator, can read, remove, add, and traverse both forward and backward, used with List implementations.

31. What is an Iterator?

The Iterator interface provides methods to iterate over any Collection in Java. Iterator is the replacement of Enumeration in the Java Collections Framework. It can get an iterator instance from a Collection using the _iterator()_ method.  It also allows the caller to remove elements from the underlying collection during the iteration.

32. Differentiate between Array and ArrayList in Java.

Array

ArrayList

Single-dimensional or multidimensional 

Single-dimensional 

For and for each used for iteration

Here iterator is used to traverse riverArrayList 

length keyword returns the size of the array. 

size() method is used to compute the size of ArrayList.

The array has Fixed-size.

ArrayList size is dynamic and can be increased or decreased in size when required.

It is faster as above we see it of fixed size

It is relatively slower because of its dynamic nature 

Primitive data types can be stored directly in unlikely objects.

Primitive data types are not directly added to unlikely arrays, they are added indirectly with help of autoboxing and unboxing

They can not be added here hence the type is in the unsafe.

They can be added here hence makingArrayList type-safe. 

The assignment operator only serves the purpose

Here a special method is used known as add() method  

33. What is the difference between Array and Collection in Java?

Array

Collections

Array in Java has a fixed size.                                        

Collections in Java have dynamic sizes.

In an Array, Elements are stored in contiguous memory locations. 

In Collections, Elements are not necessarily stored in contiguous memory locations.

Objects and primitive data types can be stored in an array.

We can only store objects in collections.

Manual manipulation is required for resizing the array.

Resizing in collections is handled automatically.

The array has basic methods for manipulation.

Collections have advanced methods for manipulation and iteration.

The array is available since the beginning of Java.

Collections were introduced in Java 1.2.

34. Difference between ArrayList and LinkedList.

ArrayList

LinkedList

ArrayList is Implemented as an expandable Array.

LinkedList is Implemented as a doubly-linked list.

In ArrayList, Elements are stored in contiguous memory locations 

LinkedList Elements are stored in non-contiguous memory locations as each element has a reference to the next and previous elements.

ArrayLists are faster for random access.

LinkedLists are faster for insertion and deletion operations

ArrayLists are more memory efficient. 

LinkedList is less memory efficient

ArrayLists Use more memory due to maintaining the array size.              

LinkedList Uses less memory as it only has references to elements

The search operation is faster in ArrayList.

The search operation is slower in LinkedList

35. Differentiate between ArrayList and Vector in Java.

ArrayList

Vector

ArrayList is implemented as a resizable array.

Vector is implemented as a synchronized, resizable array.

ArrayList is not synchronized. 

The vector is synchronized.

ArrayLists are Faster for non-concurrent operations.

Vector is Slower for non-concurrent operations due to added overhead of synchronization.

ArrayLists were Introduced in Java 1.2.

Vector was Introduced in JDK 1.0.

Recommended for use in a single-threaded environment.

Vectors are Recommended for use in a multi-threaded environment.

The default initial capacity of ArrayLists is 10.

In Vectors, the default initial capacity is 10 but the default increment is twice the size.

ArrayList performance is high.

Vector performance is low.

36. What is the difference between Iterator and ListIterator?

Iterator

ListIterator

Can traverse elements present in Collection only in the forward direction.                                          

Can traverse elements present in Collection both in forward and backward directions.

Used to traverse Map, List and Set.

Can only traverse List and not the other two.

Indexes can't be obtained using Iterator

It has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing the List.

Can't modify or replace elements present in Collection

Can modify or replace elements with the help of set(E e)

Can't add elements and also throws ConcurrentModificationException.

Can easily add elements to a collection at any time.

Certain methods of Iterator are next(), remove() and hasNext().

Certain methods of ListIterator are next(), previous(), hasNext(), hasPrevious(), add(E e).

37. Differentiate between HashMap and HashTable.

HashMap

HashTable

HashMap is not synchronized

HashTable is synchronized

One key can be a NULL value

NULL values not allowed

The iterator is used to traverse HashMap.

Both Iterator and Enumertor can be used

HashMap is faster.

HashTable is slower as compared to HashMap.

38. What is the difference between Iterator and Enumeration?

Iterator

Enumeration

The Iterator can traverse both legacies as well as non-legacy elements.

Enumeration can traverse only legacy elements.

The Iterator is fail-fast.

Enumeration is not fail-fast.

The Iterators are slower.

Enumeration is faster.

The Iterator can perform a remove operation while traversing the collection.

The Enumeration can perform only traverse operations on the collection.

39. What is the difference between Comparable and Comparator?

Comparable

Comparator

The interface is present in java.lang package.

The Interface is present in java.util package.

Provides compareTo() method to sort elements.

Provides compare() method to sort elements.

It provides single sorting sequences.

It provides multiple sorting sequences.

The logic of sorting must be in the same class whose object you are going to sort.

The logic of sorting should be in a separate class to write different sorting based on different attributes of objects.

Method sorts the data according to fixed sorting order.

Method sorts the data according to the customized sorting order.

It affects the original class.

It doesn't affect the original class.

Implemented frequently in the API by Calendar, Wrapper classes, Date and String.

It is implemented to sort instances of third-party classes.

40. What is the difference between Set and Map?

Set

Map

The Set interface is implemented using java.util package.

The map is implemented using java.util package.

It can extend the collection interface.

It does not extend the collection interface.

It does not allow duplicate values.

It allows duplicate values.

The set can sort only one null value (in HashSet/LinkedHashSet).

The map can sort multiple null values.

41. Explain the FailFast iterator and FailSafe iterator along with examples for each.

A FailFast iterator is an iterator that throws a ConcurrentModificationException if it detects that the underlying collection has been modified while the iterator is being used. This is the default behavior of iterators in the Java Collections Framework. For example, the iterator for a HashMap is FailFast.

Example:

Java
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class GFG {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");

        Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, String> entry = iterator.next();
            // this will throw a ConcurrentModificationException
            if (entry.getKey() == 1) {
                map.remove(1); 
            }
        }
    }
}

Output:

Exception in thread "main" java.util.ConcurrentModificationException

A FailSafe iterator does not throw a ConcurrentModificationException if the underlying collection is modified while the iterator is being used. Alternatively, it creates a snapshot of the collection at the time the iterator is created and iterates over the snapshot. For example, the iterator for a ConcurrentHashMap is FailSafe.

Example:

Java
import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class GFG {
    public static void main(String[] args) {
        ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
        map.put(1, "one");
        map.put(2, "two");

        Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, String> entry = iterator.next();
            // this will not throw an exception
            if (entry.getKey() == 1) {
                map.remove(1);
            }
        }
    }
}

Article Tags :

Explore