0% found this document useful (0 votes)
7 views15 pages

100 Tricky Java Collection Interview Questions.

The document contains 100 Java collections interview questions covering core concepts, lists, sets, maps, iterators, concurrency, and advanced topics. It provides detailed explanations of key interfaces, differences between various collection types, and their internal workings. Additionally, it addresses performance considerations and time complexities of operations on different collections.

Uploaded by

naibataunga1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

100 Tricky Java Collection Interview Questions.

The document contains 100 Java collections interview questions covering core concepts, lists, sets, maps, iterators, concurrency, and advanced topics. It provides detailed explanations of key interfaces, differences between various collection types, and their internal workings. Additionally, it addresses performance considerations and time complexities of operations on different collections.

Uploaded by

naibataunga1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

100 java collections interview questions

Core Concepts and Basics


1. What is the Java Collections Framework?

The Java Collections Framework is a unified architecture for representing and manipulating
collections. It provides interfaces (like List , Set , Map ), implementations (like ArrayList ,
HashSet , HashMap ), and algorithms (like sorting and searching) to work with groups of
objects.

2. What are the main interfaces in the Java Collections Framework?

The main interfaces are:


Collection : Root interface for all collections.
List : Ordered collection that allows duplicates.
Set : Unordered collection that does not allow duplicates.
Map : Stores key-value pairs (not a true collection but part of the framework).
Queue : Represents a collection designed for holding elements prior to processing.

3. What is the difference between Collection and Collections in Java?

Collection is an interface that represents a group of objects as a single unit.


Collections is a utility class that provides static methods to operate on or return collections
(e.g., sort() , reverse() , synchronizedList() ).

4. What are the key differences between List , Set , and Map ?

List : Ordered, allows duplicates, accessed by index.


Set : Unordered, does not allow duplicates.
Map : Stores key-value pairs, keys are unique.

5. What is the difference between ArrayList and LinkedList ?

ArrayList : Backed by a dynamic array, fast random access, slower insertions/deletions in the
middle.

Page 1 of 15
LinkedList : Backed by a doubly-linked list, slower random access, faster insertions/deletions
in the middle.

6. What is the difference between HashSet and TreeSet ?

HashSet : Backed by a hash table, unordered, allows null .


TreeSet : Backed by a Red-Black tree, sorted (natural order or custom comparator), does not
allow null .

7. What is the difference between HashMap and TreeMap ?

HashMap : Backed by a hash table, unordered, allows one null key and multiple null values.
TreeMap : Backed by a Red-Black tree, sorted (natural order or custom comparator), does not
allow null keys.

8. What is the difference between HashMap and Hashtable ?

HashMap : Not thread-safe, allows one null key and multiple null values.
Hashtable : Thread-safe, does not allow null keys or values.

9. What is the difference between Comparable and Comparator ?

Comparable : A single method interface ( compareTo() ) used for natural ordering of objects.
Comparator : A separate interface ( compare() ) used for custom ordering of objects.

10. What is the contract between equals() and hashCode() methods?

If two objects are equal according to equals() , they must have the same hashCode() .
However, two objects with the same hashCode() may not be equal according to equals() .

Lists
11. How does ArrayList work internally in Java?

ArrayList is backed by a dynamic array. When the array is full, it automatically resizes by
creating a new array with double the capacity and copying the elements.

12. What is the default initial capacity of an ArrayList ?

The default initial capacity of an ArrayList is 10.

Page 2 of 15
13. How does LinkedList work internally in Java?

LinkedList is backed by a doubly-linked list. Each element (node) contains a reference to the
previous and next elements, allowing efficient insertions and deletions.

14. What is the difference between ArrayList and Vector ?

ArrayList : Not thread-safe, faster.


Vector : Thread-safe (synchronized), slower.

15. Why is ArrayList not thread-safe?

ArrayList is not thread-safe because its methods are not synchronized. Concurrent
modifications can lead to inconsistent behavior or ConcurrentModificationException .

16. How can you synchronize an ArrayList ?

You can use Collections.synchronizedList(new ArrayList<>()) to create a


synchronized version of an ArrayList .

17. What is the time complexity of ArrayList operations (add, remove, get)?

Add: O(1) (amortized) for adding at the end, O(n) for adding at a specific index.
Remove: O(n) (due to shifting of elements).
Get: O(1) (constant time).

18. What is the time complexity of LinkedList operations (add, remove, get)?

Add: O(1) for adding at the beginning or end, O(n) for adding at a specific index.
Remove: O(1) for removing from the beginning or end, O(n) for removing from a specific index.
Get: O(n) (traversal required).

19. How does the sublist() method work in ArrayList ?

The sublist() method returns a view of a portion of the original list. Changes to the sublist are
reflected in the original list and vice versa.

20. What happens if you modify the original list after creating a sublist?

If the original list is structurally modified (e.g., elements are added or removed), the sublist
becomes invalid, and any operation on it will throw a ConcurrentModificationException .
Here’s the next batch of 10 questions along with their answers.

Page 3 of 15
Sets

21. How does HashSet ensure uniqueness of elements?

HashSet uses the hashCode() and equals() methods to ensure uniqueness. If two
objects have the same hashCode() and are equal according to equals() , they are
considered duplicates.

22. What is the internal implementation of HashSet ?

HashSet is internally backed by a HashMap . The elements of the HashSet are stored as keys
in the HashMap , and the values are a dummy constant ( PRESENT ).

23. What is the difference between HashSet and LinkedHashSet ?

HashSet : Unordered, does not maintain insertion order.


LinkedHashSet : Maintains insertion order using a linked list.

24. How does TreeSet maintain order?

TreeSet maintains order by using a Red-Black tree (a self-balancing binary search tree).
Elements are sorted either by their natural order or by a custom Comparator .

25. What is the time complexity of TreeSet operations?

Add: O(log n)
Remove: O(log n)
Contains: O(log n)

26. Can you add null to a HashSet ? What about TreeSet ?

HashSet : Allows one null element.


TreeSet : Does not allow null elements (throws NullPointerException ).

27. What is the difference between HashSet and TreeSet in terms of performance?

HashSet : Faster for add, remove, and contains operations (O(1) on average).
TreeSet : Slower for add, remove, and contains operations (O(log n)) but maintains sorted order.

28. How does LinkedHashSet maintain insertion order?

Page 4 of 15
LinkedHashSet maintains a doubly-linked list alongside the hash table, which preserves the
order in which elements were inserted.

29. What is the difference between Set and List ?

Set : Does not allow duplicates, unordered (except LinkedHashSet and TreeSet ).
List : Allows duplicates, maintains insertion order.

30. Can you store duplicate elements in a Set ? Why or why not?

No, a Set does not allow duplicate elements. It uses the hashCode() and equals()
methods to ensure uniqueness.
Here’s the next batch of 10 questions along with their answers.

Maps

31. How does HashMap work internally in Java?

HashMap uses an array of Node objects (buckets) to store key-value pairs. It uses the
hashCode() of the key to determine the bucket index. If a collision occurs (same bucket index),
it uses a linked list or a balanced tree (Java 8+) to store multiple entries.

32. What is the default initial capacity of a HashMap ?

The default initial capacity of a HashMap is 16.

33. What is the load factor of a HashMap ?

The default load factor of a HashMap is 0.75. It determines when the HashMap will resize
(rehash) its internal array.

34. How does HashMap handle collisions?

Collisions are handled using chaining. If two keys hash to the same bucket, they are stored in a
linked list or a balanced tree (Java 8+ for performance optimization).

35. What is the difference between HashMap and LinkedHashMap ?

HashMap : Does not maintain any order.


LinkedHashMap : Maintains insertion order or access order (if configured).

Page 5 of 15
36. How does TreeMap maintain order?

TreeMap maintains order by using a Red-Black tree (a self-balancing binary search tree). Keys
are sorted either by their natural order or by a custom Comparator .

37. What is the time complexity of HashMap operations (put, get, remove)?

Put: O(1) on average, O(n) in the worst case (due to collisions).


Get: O(1) on average, O(n) in the worst case.
Remove: O(1) on average, O(n) in the worst case.

38. What is the time complexity of TreeMap operations?

Put: O(log n)
Get: O(log n)
Remove: O(log n)

39. Can you store null keys and values in a HashMap ? What about TreeMap ?

HashMap : Allows one null key and multiple null values.


TreeMap : Does not allow null keys (throws NullPointerException ), but allows null
values.

40. What is the difference between HashMap and ConcurrentHashMap ?

HashMap : Not thread-safe, allows one null key and multiple null values.
ConcurrentHashMap : Thread-safe, does not allow null keys or values, uses finer-grained
locking for better concurrency.

Iterators and Comparators

41. What is the difference between Iterator and ListIterator ?

Iterator : Can traverse elements in a collection in one direction (forward).


ListIterator : Can traverse elements in both directions (forward and backward) and supports
additional operations like add() , set() , and previous() .

42. How does the fail-fast iterator work in Java?

A fail-fast iterator throws a ConcurrentModificationException if the collection is


modified (structurally) while iterating over it, except through the iterator's own methods.

Page 6 of 15
43. What is the difference between fail-fast and fail-safe iterators?

fail-fast : Throws ConcurrentModificationException if the collection is modified


during iteration.
fail-safe : Does not throw exceptions; works on a clone of the collection (e.g.,
ConcurrentHashMap ).

44. How do you sort a List using Comparator ?

Use the Collections.sort() method with a custom Comparator :

Collections.sort(list, Comparator.comparing(MyClass::getField));

45. How do you sort a Set using Comparator ?

Convert the Set to a List and sort it, or use a TreeSet with a custom Comparator :

Set<MyClass> sortedSet = new TreeSet<>(Comparator.comparing(MyClass::

46. How do you sort a Map by keys or values?

Sort by keys:

Map<Key, Value> sortedMap = new TreeMap<>(map);

Sort by values:

List<Map.Entry<Key, Value>> list = new ArrayList<>(map.entrySet());


list.sort(Map.Entry.comparingByValue());

47. What is the difference between Comparable and Comparator ?

Comparable : Defines natural ordering within the class (single method: compareTo() ).
Comparator : Defines custom ordering outside the class (single method: compare() ).

48. Can you use Comparator with TreeSet ?

Yes, you can pass a Comparator to the TreeSet constructor to define custom ordering:

Set<MyClass> set = new TreeSet<>(Comparator.comparing(MyClass::getFie

Page 7 of 15
49. How do you reverse a List in Java?

Use Collections.reverse() :

Collections.reverse(list);

50. How do you shuffle a List in Java?

Use Collections.shuffle() :

Collections.shuffle(list);

Concurrency in Collections

51. What is the difference between Vector and ArrayList in terms of thread safety?

Vector : Thread-safe (synchronized methods), slower.


ArrayList : Not thread-safe, faster.

52. How does Collections.synchronizedList() work?

It wraps a List (e.g., ArrayList ) and provides synchronized methods to make it thread-safe.
Example:

List<String> syncList = Collections.synchronizedList(new ArrayList<>

53. What is the difference between Hashtable and ConcurrentHashMap ?

Hashtable : Fully synchronized (thread-safe), slower.


ConcurrentHashMap : Uses finer-grained locking (thread-safe), faster.

54. How does ConcurrentHashMap achieve thread safety?

It divides the map into segments (Java 7) or uses CAS (Compare-And-Swap) and fine-grained
locks (Java 8+), allowing multiple threads to read and write concurrently without blocking.

55. What is the difference between ConcurrentHashMap and HashMap ?

HashMap : Not thread-safe, allows one null key and multiple null values.
ConcurrentHashMap : Thread-safe, does not allow null keys or values.

Page 8 of 15
56. What is the difference between CopyOnWriteArrayList and ArrayList ?

ArrayList : Not thread-safe, throws ConcurrentModificationException during


concurrent modifications.
CopyOnWriteArrayList : Thread-safe, creates a new copy of the list on modification,
allowing safe iteration.

57. What is the difference between CopyOnWriteArraySet and HashSet ?

HashSet : Not thread-safe, throws ConcurrentModificationException during


concurrent modifications.
CopyOnWriteArraySet : Thread-safe, backed by a CopyOnWriteArrayList , creates a
new copy on modification.

58. How does BlockingQueue work in Java?

BlockingQueue is a thread-safe queue that supports operations that wait for the queue to
become non-empty when retrieving an element and wait for space to become available when
storing an element.

59. What is the difference between PriorityQueue and BlockingQueue ?

PriorityQueue : Not thread-safe, orders elements based on natural order or a Comparator .


BlockingQueue : Thread-safe, supports blocking operations (e.g., put() , take() ).

60. What is the difference between ConcurrentHashMap and


Collections.synchronizedMap() ?

ConcurrentHashMap : Thread-safe, uses finer-grained locking, allows concurrent read/write


operations.
Collections.synchronizedMap() : Thread-safe, uses a single lock for the entire map,
slower for concurrent access.

Advanced Topics

61. What is the difference between EnumSet and HashSet ?

EnumSet : Specialized for enum types, highly optimized for performance, internally uses a bit
vector.
HashSet : General-purpose, works with any object type, uses a hash table.

Page 9 of 15
62. How does WeakHashMap work in Java?

WeakHashMap uses weak references for keys. If a key is no longer in use (no strong references),
it is automatically removed from the map during garbage collection.

63. What is the difference between WeakHashMap and HashMap ?

WeakHashMap : Keys are weakly referenced, allowing them to be garbage collected.


HashMap : Keys are strongly referenced, preventing garbage collection.

64. What is the purpose of IdentityHashMap in Java?

IdentityHashMap uses reference equality ( == ) instead of object equality ( equals() ) for


keys. It is useful when you need to compare objects by their memory address.

65. What is the difference between IdentityHashMap and HashMap ?

IdentityHashMap : Uses == for key comparison.


HashMap : Uses equals() and hashCode() for key comparison.

66. How does LinkedHashMap maintain insertion order?

LinkedHashMap maintains a doubly-linked list alongside the hash table, which preserves the
order in which entries were inserted.

67. What is the difference between LinkedHashMap and HashMap ?

LinkedHashMap : Maintains insertion order or access order (if configured).


HashMap : Does not maintain any order.

68. How does PriorityQueue work internally in Java?

PriorityQueue is implemented using a binary heap. Elements are ordered based on their
natural order or a custom Comparator .

69. What is the difference between PriorityQueue and TreeSet ?

PriorityQueue : Allows duplicate elements, ordered by priority.


TreeSet : Does not allow duplicates, maintains sorted order.

70. How do you implement a custom Comparator for a PriorityQueue ?

Page 10 of 15
Pass a Comparator to the PriorityQueue constructor:

PriorityQueue<MyClass> pq = new PriorityQueue<>(Comparator.comparing

Here’s the next batch of 10 questions along with their answers.

Performance and Optimization

71. What is the time complexity of HashSet operations?

Add: O(1) on average, O(n) in the worst case (due to collisions).


Remove: O(1) on average, O(n) in the worst case.
Contains: O(1) on average, O(n) in the worst case.

72. What is the time complexity of TreeSet operations?

Add: O(log n)
Remove: O(log n)
Contains: O(log n)

73. What is the time complexity of HashMap operations?

Put: O(1) on average, O(n) in the worst case (due to collisions).


Get: O(1) on average, O(n) in the worst case.
Remove: O(1) on average, O(n) in the worst case.

74. What is the time complexity of TreeMap operations?

Put: O(log n)
Get: O(log n)
Remove: O(log n)

75. How does resizing work in HashMap ?

When the number of elements exceeds the threshold (capacity * load factor), the HashMap
creates a new array with double the capacity and rehashes all the elements.

76. What is the impact of a high load factor on HashMap performance?

A high load factor reduces memory usage but increases the likelihood of collisions, degrading
performance.

Page 11 of 15
77. How does TreeMap maintain balance?

TreeMap uses a Red-Black tree (a self-balancing binary search tree) to ensure that operations
like insertions, deletions, and searches remain efficient (O(log n)).

78. What is the difference between O(1) and O(log n) in terms of performance?

O(1) : Constant time, performance does not depend on input size.


O(log n) : Logarithmic time, performance grows slowly as input size increases.

79. How do you optimize the performance of a HashMap ?

Use an appropriate initial capacity and load factor.


Ensure keys have a good hashCode() implementation to minimize collisions.

80. What is the impact of using a poor hashCode() implementation on HashMap performance?

A poor hashCode() implementation can lead to many collisions, degrading performance from
O(1) to O(n) in the worst case.

Common Pitfalls and Best Practices

81. What happens if you modify a HashMap while iterating over it?

If you modify a HashMap structurally (add/remove elements) while iterating over it, it will throw a
ConcurrentModificationException .

82. What happens if you add duplicate keys to a HashMap ?

Adding a duplicate key will overwrite the existing value associated with that key.

83. What happens if you add duplicate elements to a HashSet ?

Adding a duplicate element to a HashSet will have no effect. The HashSet will remain
unchanged.

84. What happens if you add null to a TreeSet ?

Adding null to a TreeSet will throw a NullPointerException because TreeSet does


not allow null elements.

85. What happens if you add null to a TreeMap ?

Page 12 of 15
Adding null as a key to a TreeMap will throw a NullPointerException because
TreeMap does not allow null keys.

86. What happens if you modify a List while iterating over it?

If you modify a List structurally (add/remove elements) while iterating over it, it will throw a
ConcurrentModificationException .

87. What happens if you modify a Set while iterating over it?

If you modify a Set structurally (add/remove elements) while iterating over it, it will throw a
ConcurrentModificationException .

88. What happens if you modify a Map while iterating over it?

If you modify a Map structurally (add/remove elements) while iterating over it, it will throw a
ConcurrentModificationException .

89. What is the best way to iterate over a Map in Java?

Use the entrySet() method to iterate over key-value pairs:

for (Map.Entry<Key, Value> entry : map.entrySet()) {


Key key = entry.getKey();
Value value = entry.getValue();
}

90. What is the best way to remove elements from a List while iterating over it?

Use an Iterator and its remove() method:

Iterator<MyClass> iterator = list.iterator();


while (iterator.hasNext()) {
MyClass element = iterator.next();
if (condition) {
iterator.remove();
}
}

Here’s the final batch of 10 questions along with their answers.

Page 13 of 15
Miscellaneous

91. What is the difference between Arrays.asList() and ArrayList ?

Arrays.asList() returns a fixed-size list backed by the original array. It does not support
structural modifications (add/remove).
ArrayList is a resizable array implementation of the List interface.

92. What is the difference between Collections.emptyList() and new ArrayList() ?

Collections.emptyList() returns an immutable, empty list.


new ArrayList() creates a mutable, empty list.

93. What is the difference between Collections.singletonList() and Arrays.asList() ?

Collections.singletonList() returns an immutable list containing a single element.


Arrays.asList() returns a fixed-size list backed by the original array.

94. How do you convert a List to an array in Java?

Use the toArray() method:

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


String[] array = list.toArray(new String[0]);

95. How do you convert an array to a List in Java?

Use Arrays.asList() :

String[] array = {"a", "b", "c"};


List<String> list = Arrays.asList(array);

96. What is the difference between Collections.sort() and Arrays.sort() ?

Collections.sort() : Sorts a List .


Arrays.sort() : Sorts an array.

97. How do you find the frequency of elements in a List ?

Use Collections.frequency() :

Page 14 of 15
int frequency = Collections.frequency(list, element);

98. How do you find the intersection of two Lists ?

Use retainAll() :

List<String> list1 = new ArrayList<>();


List<String> list2 = new ArrayList<>();
list1.retainAll(list2); // list1 now contains the intersection.

99. How do you find the union of two Sets ?

Use addAll() :

Set<String> set1 = new HashSet<>();


Set<String> set2 = new HashSet<>();
set1.addAll(set2); // set1 now contains the union.

100. How do you implement a custom collection in Java?

Extend an existing collection class (e.g., AbstractList , AbstractSet ) or implement the


relevant interface (e.g., List , Set ) and override the required methods.

That’s it! You’ve now gone through 100 tricky Java Collection interview questions.

Page 15 of 15

You might also like