34 Java Collections Interview Questions and Answers

This page covers frequently asked Java Collections interview questions, providing explanations and comparisons of key data structures.

What is the Java Collections Framework?

The Java Collections Framework is a set of classes and interfaces designed for storing and manipulating groups of objects. It provides various implementations like ArrayList, HashSet, and TreeMap, and interfaces like List, Set, and Map to define different types of collections.

Arrays vs. Collections

Feature Array Collection
Size Fixed Dynamic
Data Type Homogeneous (same type) Heterogeneous (different types)
Built-in Methods Limited Rich set of methods (sorting, searching, etc.)

Collection Framework Interfaces

The Java Collections Framework is built around several key interfaces:

  1. Collection (the root interface)
  2. List (ordered, allows duplicates)
  3. Set (unordered, no duplicates)
  4. Queue (FIFO - First In, First Out)
  5. Deque (double-ended queue, supports both FIFO and LIFO)
  6. Map (key-value pairs)

ArrayList vs. Vector

Feature ArrayList Vector
Synchronization Not synchronized Synchronized
Legacy Class No Yes
Size Increase 50% Doubles
Thread Safety Not thread-safe Thread-safe

ArrayList vs. LinkedList

Feature ArrayList LinkedList
Implementation Dynamic array Doubly linked list
Data Manipulation Less efficient More efficient
Data Access Fast random access No random access
Memory Overhead Lower Higher

Iterator vs. ListIterator

Feature Iterator ListIterator
Traversal Direction Forward only Forward and backward
Usable with List, Set, Queue List only
Operations remove() add(), remove(), set()

Iterator vs. Enumeration

Feature Iterator Enumeration
Element Types Legacy and non-legacy Legacy only
Fail-Fast Yes No
Speed Slower Faster
Operations remove() hasMoreElements(), nextElement()

List vs. Set

Feature List Set
Duplicates Allowed Not allowed
Order Ordered (insertion order) Unordered
Null Values Multiple nulls allowed One null allowed

HashSet vs. TreeSet

Feature HashSet TreeSet
Order No order Ascending order
Implementation Hash table Tree structure
Speed Faster Slower

Set vs. Map

Feature Set Map
Contents Values only Key-value pairs
Duplicates No duplicates Unique keys, duplicate values allowed
Nulls One null allowed One null key, multiple null values allowed

HashSet vs. HashMap

Feature HashSet HashMap
Contents Values only Key-value pairs
Interface Set Map
Duplicates No duplicates Unique keys, duplicate values allowed
Nulls One null allowed One null key, multiple null values allowed

HashMap vs. TreeMap

Feature HashMap TreeMap
Order No order Ascending order (by key)
Implementation Hash table Tree structure
Sorting Can be sorted (requires extra effort) Sorted by key
Null Key One null key allowed No null key allowed

HashMap vs. Hashtable

Feature HashMap Hashtable
Synchronization Not synchronized Synchronized
Nulls One null key, multiple null values allowed No nulls allowed
Thread Safety Not thread-safe Thread-safe

Collection vs. Collections

Feature Collection Collections
Type Interface Class
Purpose Defines collection functionality Provides utility methods for collections

Comparable vs. Comparator

Feature Comparable Comparator
Sorting Single sorting order Multiple sorting orders
Method compareTo() compare()
Class Modification Modifies the class Does not modify the class

BlockingQueue

BlockingQueue is a thread-safe queue interface that blocks operations (put or take) until space is available or an element is present.

Advantages of Properties Files

Changes to properties files don't require recompilation, making configuration easier to manage.

Example Properties File Usage

Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
String myValue = prop.getProperty("myKey");

The Java Collections Framework

The Java Collections Framework is a unified architecture for representing and manipulating collections of objects. It provides interfaces (like List, Set, Map, and Queue) and concrete classes (like ArrayList, HashSet, and TreeMap) to handle various data structures.

`hashCode()` Method

The hashCode() method returns an integer hash code value for an object. If two objects are equal (according to the `equals()` method), their hash codes *should* be the same. However, it's possible for different objects to have the same hash code (a collision).

Why Override `equals()`?

The `equals()` method checks for object equality. You need to override it if you want to define equality based on specific object properties rather than just memory addresses (references).

Synchronizing Collections

The Collections class provides methods to create synchronized versions of Lists, Sets, and Maps:

  • Collections.synchronizedList(List l)
  • Collections.synchronizedSet(Set s)
  • Collections.synchronizedSortedSet(SortedSet s)
  • Collections.synchronizedMap(Map m)
  • Collections.synchronizedSortedMap(SortedMap m)

Advantages of Generic Collections

  • Eliminates the need for typecasting.
  • Provides compile-time type safety.
  • Improves code robustness by catching type errors during compilation.

Hash Collisions

A hash collision occurs when two different keys produce the same hash code. Techniques like separate chaining and open addressing are used to handle collisions in hash tables.

`Dictionary` Class

The Dictionary class (mostly obsolete) stores key-value pairs. It's a legacy class and generally not recommended for new code (use HashMap or Hashtable instead).

Default Load Factor in Hashing-Based Collections

The default load factor for hashing-based collections (like HashMap) is 0.75. The capacity is calculated as initialCapacity * loadFactor.

Fail-Fast Iterators

Fail-fast iterators immediately throw a ConcurrentModificationException if the collection is structurally modified (added to or removed from) while iteration is in progress.

`Array` vs. `ArrayList`

Feature `Array` `ArrayList`
Size Fixed Dynamic
Type Static Dynamic
Data Types Primitives and objects Objects only

Array Length vs. `ArrayList` Size

Use `array.length` to get the length of an array. Use `arrayList.size()` to get the number of elements in an ArrayList.

Example: Array Length and ArrayList Size

int[] array = new int[4];
System.out.println("Array length: " + array.length); // Output: 4

ArrayList<String> list = new ArrayList<>();
list.add("ankit");
list.add("nippun");
System.out.println("ArrayList size: " + list.size()); // Output: 2

Converting Between `ArrayList` and Array

  • Array to `ArrayList` : Arrays.asList(array)
  • `ArrayList` to Array: list.toArray(new Object[list.size()])

Making an `ArrayList` Read-Only

Use Collections.unmodifiableList(list) to create a read-only view of an ArrayList. Attempting to modify the list will throw an exception.

Removing Duplicates from `ArrayList`

Use a LinkedHashSet to maintain insertion order while removing duplicates, or a HashSet if order isn't important.

  1. Copy the ArrayList to a LinkedHashSet.
  2. Clear the original ArrayList.
  3. Copy the LinkedHashSet back to the ArrayList.

Reversing an `ArrayList`

Use Collections.reverse(list).

Example: Reversing an ArrayList

List<Integer> list = new ArrayList<>();
// ... add elements ...
Collections.reverse(list);

Sorting an `ArrayList` in Descending Order

Use Collections.sort(list, Collections.reverseOrder()).

Example: Sorting in Descending Order

List<Integer> list = new ArrayList<>();
// ... add elements ...
Collections.sort(list, Collections.reverseOrder());

Synchronizing an `ArrayList`

  • Use Collections.synchronizedList(list).
  • Use CopyOnWriteArrayList (creates a copy on each modification).

When to Use `ArrayList` vs. `LinkedList`

Use ArrayList for frequent data access (retrieval); use LinkedList for frequent insertions and deletions.