Open In App

Collections & Generics Interview Questions - Java Programming

Last Updated : 08 Aug, 2025
Comments
Improve
Suggest changes
Like Article
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 Collection Framework in Java?

Collections are units 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. Explain various interfaces used in the Collection framework.

Collection framework implements

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

Collection interface: Collection is the primary interface available that can be imported using java.util.Collection.

Syntax:

public interface Collection<E> extends iterable

3. How can you synchronize an ArrayList in Java?

An ArrayList can be synchronized using two methods mentioned below:

  1. Using Collections.synchronizedList()
  2. Using CopyOnWriteArrayList

Using Collections.synchronizedList():

public static List<T> synchronizedList(List<T> list)

Using CopyOnWriteArrayList:

  1. Create an empty List.
  2. It implements the List interface
  3. It is a thread-safe variant of ArrayList
  4. T represents generic

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

ArrayList is in need even when we have Vectors because of certain reasons:

  1. ArrayList is faster than Vectors.
  2. ArrayList supports multithreading whereas Vectors only supports single-thread use.
  3. ArrayList is safer to use, as Vectors supports single threads and individual operations are less safe and take longer to synchronize.
  4. Vectors are considered outdated in Java because of their synchronized nature.

5. 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.

6. Can you explain how elements are stored in memory for both regular arrays and ArrayLists in Java? . Explain.

The elements of a regular array in Java are stored in contiguous memory locations, meaning that each element is stored in a sequential block of memory. This allows easy access to any element by its index because the address can be calculated using the base address of the array and the size of each element

In contrast, the ArrayList class implements a dynamic array, which means that its size can change as elements are added or removed. ArrayList elements are also stored in contiguous memory locations, similar to arrays. However, when an ArrayList reaches its capacity and more elements need to be added, a new, larger underlying array is created. The elements from the old array are then copied to the new one. This process ensures that the ArrayList can grow dynamically while keeping the elements in contiguous memory locations.

7. Explain the method to convert ArrayList to Array and Array to ArrayList.

Conversion of List to ArrayList

There are multiple methods to convert List 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
// Java program to demonstrate conversion of
// Array to ArrayList of fixed-size.
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]

Conversion of ArrayList to Array:

Convert-ArrayList-to-Array-768


Java programmers can convert ArrayList to

Syntax:

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

Example:

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 

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

Due to ArrayLists array-based nature, it grows dynamically in size ensuring that there is always enough room for elements. When an ArrayList element is first created, the default capacity is around 10-16 elements which basically depends on the Java version. ArrayList elements are copied over from the original array to the new array when the capacity of the original array is full. As the ArrayList size increases dynamically, the class creates a new array of bigger sizes and it copies all the elements from the old array to the new array. Now, the reference of the new array is used internally. This process of dynamically growing an array is known as resizing. 

9. What is a Vector in Java?

Vectors in Java are similar and can store multiple elements inside them. Vectors follow certain rules mentioned below:

  1. Vector can be imported using Java.util.Vector.
  2. Vector is implemented using a dynamic array as the size of the vector increases and decreases depending upon the elements inserted in it. 
  3. Elements of the Vector using index numbers.
  4. Vectors are synchronized in nature means they only used a single thread ( only one process is performed at a particular time ).
  5. The vector contains many methods that are not part of the collections framework.

Syntax:

Vector gfg = new Vector(size, increment);

10. 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

11. 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

12. Explain the LinkedList class.

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

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

Syntax:

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

13. 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

14. What is Set in the Java Collections framework and list down its various implementations?

Sets are collections that don't store duplicate elements. They don't keep any order of the elements. The Java Collections framework provides several implementations of the Set interface, including:

  • HashSet: HashSet in Java, stores the elements in a has table which provides faster lookups and faster insertion. HashSet is not ordered.
  • LinkedHashSet: LinkedHashSet is an implementation of HashSet which maintains the insertion order of the elements.
  • TreeSet: TreeSet stores the elements in a sorted order that is determined by the natural ordering of the elements or by a custom comparator provided at the time of creation.

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

The HashSet class implements the Set interface in the Java Collections Framework and is a member of the HashSet class. Unlike duplicate values, it stores a collection of distinct elements. In this implementation, each element is mapped to an index in an array using a hash function, and the index is used to quickly access the element. It produces an index for the element in the array where it is stored based on the input element. Assuming the hash function distributes the elements among the buckets appropriately, the HashSet class provides constant-time performance for basic operations (add, remove, contain, and size).

16. 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]

17. 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:

  1. SortedMap
  2. TreeMap
  3. HashMap
  4. LinkedHashMap

18. Explain Treemap in Java

TreeMap is a type of map that stores data in the form of key-value pair. It is implemented using the red-black tree. Features of TreeMap are :

  1. It contains only unique elements.
  2. It cannot have a NULL key 
  3. It can have multiple NULL values.
  4. It is non-synchronized.
  5. It maintains ascending order.

19. What is EnumSet?

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

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

Syntax:

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

Parameter: E specifies the elements.

20. 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

21. What is the ConcurrentHashMap in Java and do you implement it?

ConcurrentHashMap is implemented using Hashtable.

Syntax:

public class ConcurrentHashMap<K, ​V>
extends AbstractMap<K, ​V>
implements ConcurrentMap<K, ​V>, Serializable

Parameters: K is the key Object type and V is the value Object type

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

Yes, we can use any class as a Map Key if it follows certain predefined rules mentioned below:

  1. The class overriding the equals() method must also override the hashCode() method
  2. The concurrentHashMap class is thread-safe.
  3. The default concurrency level of ConcurrentHashMap is 16.
  4. Inserting null objects in ConcurrentHashMap is not possible as a key or as value.

23. What is an Iterator?

Iterator-in-Java-768

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.

24. What is an enumeration?

Enumeration is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. The main objective of the enum is to define user-defined data types.

Example:

// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
RED, GREEN, BLUE;
}

25. What is the difference between Collection and Collections?

Collection

Collections

The Collection is an Interface.

Collections is a class.

It provides the standard functionality of data structure.

It is to sort and synchronize the collection elements.

It provides the methods that can be used for the data structure.

It provides static methods that can be used for various operations.

26. 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  

27. 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.

28. 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

29. 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.

30. 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).

31. 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 Enumertar can be used

HashMap is faster.

HashTable is slower as compared to HashMap.

32. 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.

33. 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.

34. 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.

The map can sort multiple null values.

35. 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 :
Practice Tags :

Similar Reads