Java

Java Java Collections Interview Questions

114 questions with answers · Java Interview Guide

ArrayList, LinkedList, HashMap, HashSet, TreeMap internals and performance. One of the most tested areas in Java interviews.

bar_chartQuick stats
Total questions114
High frequency5
With code examples8
1

Tell me about the hierarchy of collections in Java

Collection → List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue; Map hierarchy separate (HashMap, TreeMap, ConcurrentHashMap).

java
Collection<Integer> col = Arrays.asList(1, 2, 3);
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<String, Integer> map = new HashMap<>();
2

What is the difference between Linkedlist and Arraylist

ArrayList uses dynamic array (fast random access, slow insertion/deletion), LinkedList uses doubly-linked nodes (slow access, fast insertion/deletion at ends).

java
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
LinkedList<Integer> ll = new LinkedList<>();
ll.addFirst(1);
ll.addLast(2);
3

How Hashmap is organized

HashMap uses array of buckets; hash function determines bucket index, collisions resolved via linked lists or red-black trees (Java 8+) when threshold exceeded.

java
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
Node node = map.getNode("a");
int index = hash("a") % capacity;
4

How Hashmap is related to SET

Set uses HashMap internally (each Set element is stored as a HashMap key with a dummy value), so Set operations inherit HashMap's O(1) average lookup performance.

java
Set<Integer> set = new HashSet<>();
Map<Integer, String> map = new HashMap<>();
set.add(1);
map.put(1, "one");
Set<Integer> mapKeys = map.keySet();
5

Tell me about Hashmap

HashMap is an unsynchronized hash table implementation that uses buckets with chaining/open addressing for collision resolution. It allows null keys/values, operates in O(1) average time, and is not thread-safe; use ConcurrentHashMap for concurrent access.

java
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
Integer val = map.get("a");
map.remove("b");
6

What is the difference between hashmap and hashtable

HashMap is unsynchronized and faster; Hashtable is synchronized (thread-safe) but slower; HashMap allows one null key/multiple null values, Hashtable doesn't allow nulls.

java
HashMap<String, Integer> hm = new HashMap<>();
hm.put("a", 1);
Hashtable<String, Integer> ht = new Hashtable<>();
ht.put("a", 1);
System.out.println(hm.get("a"));
System.out.println(ht.get("a"));
7

What is the difference between Treeset and Hashset

TreeSet maintains sorted order (O(log n) operations) using Red-Black tree; HashSet uses hash table for O(1) average operations without ordering.

java
TreeSet<Integer> ts = new TreeSet<>();
ts.addAll(Arrays.asList(3, 1, 2));
HashSet<Integer> hs = new HashSet<>();
hs.addAll(Arrays.asList(3, 1, 2));
System.out.println(ts);
System.out.println(hs);
8

Why MAP stands apart in the hierarchy of collections

Map doesn't extend Collection interface; it's a key-value structure with different iteration patterns (entrySet, keySet, values) rather than single-element containers.

java
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
Collection<Integer> values = map.values();
System.out.println(values);
System.out.println(map.keySet());
9

Tell me about the Collection Framework hierarchy

Collection hierarchy: Iterable → Collection → List/Set/Queue; List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue (PriorityQueue); Map is separate (HashMap, TreeMap).

10

Array of static data structure or dynamic

Arrays are static data structures with fixed size allocated at creation; you must copy to a larger array for resizing, unlike dynamic structures.

11

What is the difference between Arraylist and vector

ArrayList is dynamic, unsynchronized, faster; Vector is synchronized (thread-safe), slower, legacy class; ArrayList should be used for new code.

12

What is Vector

Vector is a synchronized, dynamic array similar to ArrayList but thread-safe; it's legacy and replaced by ArrayList with external synchronization when needed.

13

What are the Java collections

Java Collections include List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue (PriorityQueue), Map (HashMap, TreeMap), and utilities like Collections class.

14

Is Hashmap a safe stream collection

HashMap is not thread-safe; use ConcurrentHashMap for concurrent access or Collections.synchronizedMap() for full synchronization.

15

What is Failfast

Fail-fast means iterators throw ConcurrentModificationException if the collection is modified during iteration; it detects concurrent modifications.

16

What is Deque

Deque (Double Ended Queue) allows insertion/removal at both ends; implementations include ArrayDeque and LinkedList, useful for stacks and queues.

17

HashTable and Concurrenthashmap - differences and what is more effective

Hashtable is synchronized (thread-safe but slower), ConcurrentHashMap uses segment-based locking allowing concurrent reads/writes, making it more effective for multi-threaded scenarios with better performance.

18

What is LIST, SET implicitly

List is an ordered, mutable collection allowing duplicates; Set is unordered and prevents duplicates; both are interfaces implemented by concrete classes.

19

What is Capacy of list

Capacity is the internal array size of a List; not the same as size (number of elements),capacity is pre-allocated to reduce resizing overhead.

20

By what principle does the number of bakers increase

ArrayList increases capacity by 50% of current size (capacity = old capacity * 1.5) when it exceeds the current limit, using System.arraycopy() for migration.

21

How to organize a search for Arraylist

ArrayList search requires linear iteration O(n) unless sorted, then use Collections.binarySearch() for O(log n) complexity.

22

Is it possible to lose an object in hashmap

No, objects aren't lost in HashMap; if you put a null key or null value, they're stored. However, if a key's hashCode/equals changes after insertion, retrieval may fail.

23

What are Java collections

Java Collections are interfaces (List, Set, Map) and implementations (ArrayList, HashMap, HashSet) that provide data structure abstractions for storing and manipulating object groups efficiently.

24

What are the implementations in the collection of the sheet interface

List interface implementations include ArrayList (dynamic array), LinkedList (doubly-linked list), Vector (synchronized legacy), and Stack (LIFO).

25

By what principle does the number of bakers increase

HashMap bucket count increases by doubling when load factor (default 0.75) is exceeded; new capacity = old capacity * 2.

26

How the process works if we want to put something in MAP or get

HashMap uses hashCode() to determine bucket index and equals() to resolve collisions; put() computes index and stores entry, get() retrieves using the same hash-based lookup.

27

What is Capacy

Capacity is the current size of HashMap's internal bucket array; initial capacity is 16, and it resizes when load factor is exceeded.

28

How much BUCKET can be in hashmap

HashMap has a default of 16 buckets initially; buckets store Entry objects (key-value pairs) in linked chains to handle hash collisions.

29

How to look and delete elements in list

Use get(index) or iterator() for lookup; use remove(index) or remove(object) for deletion from Lists.

30

How can we bypass the elements of the collection

Iterate using Iterator, enhanced for-loop, forEach(Consumer), stream().forEach(), or Enumeration (legacy) depending on collection type.

31

What is the difference between Hashset and LinkedHashset

HashSet is unordered with O(1) operations; LinkedHashSet maintains insertion order using a doubly-linked list, slower than HashSet due to extra overhead.

32

Whether I heard something about SET

SET is a Collection interface for unordered, unique elements; implementations include HashSet (hash-based), TreeSet (sorted), and LinkedHashSet (insertion-ordered).

33

What needs to be done to use the Foreach cycle

Implement Iterable interface or use arrays/Collections; allows using enhanced for-loop syntax with any custom collection.

34

Can it be that in Hashmap there will be two identical keys

No, HashMap allows only one null key and multiple null values; duplicate keys overwrite previous values silently.

35

What restriction is to add to Treeset

Elements must be Comparable (implement Comparator) or natural ordering fails; TreeSet cannot store non-comparable objects.

36

Can Treeset store null

No, TreeSet doesn't allow null values; throws NullPointerException due to compareTo() null checks in ordering.

37

What are the main implementations about the collection

List (ArrayList, LinkedList), Set (HashSet, TreeSet), Map (HashMap, TreeMap); Queue and Deque are specialized subtypes.

38

What is the level of complexity in Hashset when looking for an element

O(1) average case for lookup; O(n) worst case if hash collisions are severe; depends on hash function quality and load factor.

39

How structurally a two -link list looks compared to the single

Doubly-linked list has next and previous pointers; singly-linked has only next; doubly allows bidirectional traversal with O(1) reverse access.

40

What will be the speed of access to the element in LinkedList, which is located in the middle

O(n) sequential access from head; middle element requires n/2 node traversals; LinkedList favors insertion/deletion over random access.

41

What will be the search speed in linkedlist

O(n) linear search; LinkedList lacks random access, requires traversal from head or tail.

42

What is the search speed in Arraylist

O(1) average case for search via contains(); O(n) worst case; backed by HashMap internally.

43

What is the speed of access to the element in Linkedlist by index

O(n) linear time; must traverse nodes sequentially, no index-based direct access.

44

What to have inside Hashset and Treeset

HashSet: Object instances with hashCode/equals; TreeSet: Comparable/Comparator objects for sorted ordering.

45

LinkedList single -legged or two -link

Java LinkedList is doubly-linked; maintains previous and next node references for bidirectional traversal.

46

Tell me about LinkedHashmap

LinkedHashMap maintains insertion order via doubly-linked list; extends HashMap with predictable iteration order.

47

What are the main JCF interfaces and their implementation

Main JCF interfaces: Collection (List, Set, Queue), Map; implementations include ArrayList, HashSet, HashMap, LinkedList, PriorityQueue, TreeSet, TreeMap.

48

What is the difference between Java.util.collection and Java.util.collections classes

Collection is an interface for single-element collections; Collections is a utility class with static methods like sort(), reverse(), unmodifiableList() for collection operations.

49

Give examples of iterators realizing Fail-Safe behavior

CopyOnWriteArrayList and CopyOnWriteArraySet use fail-safe iteration by creating snapshots, avoiding ConcurrentModificationException during concurrent modifications.

50

How the enumeration and iterator differ

Enumeration is legacy, unidirectional (hasMoreElements/nextElement), doesn't support removal; Iterator is newer, bidirectional with remove(), and preferred.

51

How it is the itrable and iterator

Iterable has iterator() method returning Iterator; Iterator has hasNext(), next(), remove(); Iterable enables for-each loops, Iterator does actual traversal.

52

How it is interconnected by iterable, iterator and “for-each”

for-each loop calls iterable.iterator() to get Iterator, then repeatedly calls hasNext() and next(); Iterable and Iterator work together to enable convenient traversal.

53

Compare Iterator and Listiterator.

Iterator is unidirectional and works with any Collection; ListIterator is bidirectional, works only with List, and allows element modification during iteration.

54

What will happen when iterator.next () call it without preliminary call iterator.hasnext ()

It throws NoSuchElementException if there are no more elements; calling hasnext() first is mandatory to avoid this.

55

How the collection behaves if it call iterator.remove ()

iterator.remove() safely removes the last element returned by next() and updates the underlying collection without causing ConcurrentModificationException.

56

How the already instituteed iterator will behave for Collection, if you call collection.remove ()

It throws ConcurrentModificationException because the iterator detects structural modification of the collection that wasn't done through its own remove() method.

57

How to avoid ConcurrentModificationException during the enforcement of the collection

Use iterator.remove() instead of collection.remove(), or use CopyOnWriteArrayList, or synchronize the collection access, or use Java 8 streams.

58

Which collection implements FIFO service discipline

Queue implements FIFO (First-In-First-Out) discipline via offer/poll operations.

59

Which collection implements the discipline of Filo service

Stack implements LIFO (Last-In-First-Out) discipline, or use Deque with push/pop methods.

60

Why added ArrayList if there was already Vector

ArrayList is unsynchronized and faster than the legacy synchronized Vector; Vector is now obsolete.

61

That works faster than Arraylist or LinkedList

ArrayList is faster for random access O(1); LinkedList is faster for insertions/deletions at the beginning O(1) vs ArrayList O(n).

62

What the worst time of the Contains () method for the element that is in LinkedList

O(n) because LinkedList must traverse sequentially from head to find the element.

63

What is the worst time of the Contains () method for the element that is in Arraylist

O(n) worst case when searching for the last element, though access is O(1).

64

What the worst time of the Add () method for linkedlist

O(1) at the end, but O(n) in the worst case when inserting at the beginning.

65

What the worst time of the Add () method for Arraylist

O(1) amortized at the end due to pre-allocated capacity; O(n) when inserting in the middle.

66

How is the removal of elements from Arraylist, how in this case the size of Arraylist changes in this case

Elements shift left to fill the gap; size decreases by 1; remaining elements maintain relative order.

67

Offer an effective algorithm for removing several nearby elements from the middle of the list implemented by Arraylist

Create a new ArrayList with the desired range using removeAll() with a filtered subset, or use ArrayList.subList().clear() to remove a contiguous range efficiently.

68

How much additional memory is needed when calling Arraylist.add ()

Roughly 50% of current capacity when exceeding threshold; ArrayList grows by 1.5x of current size.

69

How much is the addition of memory when calling linkedlist.add ()

16-32 bytes per node (varies by JVM) for Node objects containing references and pointers, not just the byte value.

70

Assess the number of memory for storage of one BYTE type primitive in LinkedList

Approximately 16-32 bytes per element for internal Node structure (next/prev pointers + references), making storage inefficient for primitives.

71

Assess the number of memory for storage of one BYTE type primitive in Arraylist

1 byte for the primitive value; ArrayList stores references, so actual memory is higher due to object wrapper overhead.

72

Compare the interfaces Queue and Deque

Queue is single-ended (add at tail, remove at head); Deque is double-ended (add/remove at both ends), supporting both FIFO and LIFO operations.

73

Who expands whom: Queue expands Deque, or Deque expands Queue

Deque expands Queue; Queue is a single-ended interface, Deque adds bidirectional access.

74

Why is LinkedList implement both List and Deque

LinkedList implements both because it efficiently supports both sequential (List) and bidirectional (Deque) operations without overhead.

75

How to sort out LinkedList elements in the reverse order without using a slow get (index)

Use descendingIterator() method which traverses the list backwards efficiently without indexed access.

76

Which allows you to make priorityqueue

Comparator interface allows you to define custom ordering for PriorityQueue elements.

77

Stack is considered "outdated", which is recommended to replace it, why

Deque (via ArrayDeque) replaces Stack; it's faster, not synchronized, and follows modern collection design patterns.

78

What is Identityhashmap for

IdentityHashMap uses reference equality (==) instead of equals() for key comparison, useful for identity-based lookups.

79

What is the difference between Hashmap and IdentityHamap

HashMap uses equals() and hashCode() for equality; IdentityHashMap uses == for reference comparison only.

80

Why is Weakhashmap used

WeakHashMap uses weak references for keys, allowing garbage collection when keys are no longer referenced elsewhere.

81

What is the difference between Hashmap and Weakhashmap

HashMap keeps strong references to keys; WeakHashMap uses WeakReference, enabling automatic removal of unreachable keys.

82

What is the “sorting” of SortedMap, in addition to the fact that tostring () displays all elements in order

SortedMap maintains keys in sorted order (per comparator or natural ordering) affecting iteration order and enabling range queries like subMap().

83

What is the assessment of temporary complexity of operations on elements from Hashmap, whether Hashmap guarantees the specified complexity of the sample of the element

O(1) average case for get/put; HashMap does NOT guarantee this,it's average case, not worst case.

84

Is the situation when Hashmap degenerates into the list even with keys having different hashcode ()

Yes, HashMap can degenerate to O(n) even with different hashCodes if hash function produces many collisions; Java 8+ mitigates this with tree-based buckets.

85

Why you can not use byte [] as a key in hashmap

byte[] uses reference-based hashCode() and equals(), not content-based, causing different arrays to be treated as different keys despite identical content.

86

What the worst time of the Get (Key) method for the key, which is not in hashmap

O(n) worst case,when all keys hash to the same bucket (all collisions) or bucket contains a tree with many entries.

87

What the worst time of the Get (Key) method for the key that is in Hashmap

O(1) average case, O(n) worst case if the key's bucket has many collisions or contains a red-black tree with traversal overhead.

88

How many transitions are at the time of calling Hashmap.get (Key) on the key that is in the table

Typically 1-2 transitions: hash the key, find the bucket, then retrieve the entry (or traverse tree if present in Java 8+).

89

How many new objects are created when you add a new element to hashmap

Usually 1 new object (the Node/Entry wrapper); 2 if key-value pair requires boxing for primitive types.

90

How and when there is an increase in the number of baskets in hashmap

Triggered when size exceeds (capacity × loadFactor); new capacity is typically double the old, then all entries are rehashed.

91

Explain the meaning of the parameters in the constructor Hashmap (Intialcapacy, Float LoadFactor)

initialCapacity sets the starting bucket count; loadFactor (default 0.75) is the threshold ratio of size to capacity triggering resize.

92

Will Hashmap work if all added keys will have the same Hashcode ()

Yes, HashMap still works but degenerates to O(n) for all operations since all keys collide in the same bucket; Java 8+ trees mitigate this somewhat.

93

How to sort all the keys Map

Use Collections.sort(map.keySet()) or stream with map.keySet().stream().sorted().collect(Collectors.toList()); for sorting keys.

94

How to sort out all MAP values

Use Collections.sort(new ArrayList<>(map.values())) or map.values().stream().sorted().collect(Collectors.toList()); for sorting values.

95

How to sort through all pairs of "key-meaning" in MAP

Use map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(...) or Collections.sort(new ArrayList<>(map.entrySet()), Map.Entry.comparingByKey()).

96

What will happen if you add elements to Treeset by increasing

TreeSet maintains elements in sorted order automatically; adding elements by increasing order ensures O(log n) insertion complexity instead of potential collisions.

97

For Enum there is a special class Java.util.enumset, why, why the authors did not suit Hashset or Treeset

EnumSet is specialized for enums with bit-vector backing, providing better performance (O(1) operations) and memory efficiency than HashSet or TreeSet which use hashing/trees.

98

What are the ways to sort out the list elements

Use Collections.sort() for natural order, Collections.sort(list, comparator) for custom order, or list.stream().sorted().collect(Collectors.toList()).

99

How can synchronized objects of standard collections be obtained

Use Collections.synchronizedList(), Collections.synchronizedSet(), Collections.synchronizedMap() which return synchronized wrapper collections.

100

How to get a collection only for reading

Use Collections.unmodifiableList(), Collections.unmodifiableSet(), Collections.unmodifiableMap() to get read-only collection views.

101

How to copy the elements of any Collection in an array with one line

Use collection.toArray() for Object array or list.toArray(new Type[0]) for typed array in one call.

102

How to convert Hashset to Arraylist one line with one line

Use new ArrayList<>(hashset) or hashset.stream().collect(Collectors.toList()).

103

How to convert Arraylist into Hashset one line with one line

Use new HashSet<>(arraylist) or arraylist.stream().collect(Collectors.toSet()).

104

Collections.emptylist () or new copy

Collections.emptyList() returns an immutable singleton that's reused, while new copy creates a new instance; use emptyList() for efficiency.

105

Whether Hashmap guarantees the specified complexity of the element sample

HashMap doesn't guarantee O(1) complexity; it's average O(1) but can degrade to O(n) on hash collisions; Java 8+ uses trees for better worst-case.

106

What is the maximum number of hashcode () values

There's no maximum number of hashCode() values; hashCode() returns int so theoretically 2^32 unique values, but multiple objects can hash to same value.

107

What are the main SET implementation

Main SET implementations: HashSet (hash-based), TreeSet (sorted/balanced tree), LinkedHashSet (insertion-order), EnumSet (bit-vector for enums).

108

What are the main implementation of MAP

Main MAP implementations: HashMap (hash-based), TreeMap (sorted/balanced tree), LinkedHashMap (insertion-order), Hashtable (legacy synchronized), ConcurrentHashMap (thread-safe).

109

Copyonwrite collection

CopyOnWriteArrayList/Set creates a copy of underlying array on modification, making reads fast but writes expensive; ideal for read-heavy concurrent scenarios.

110

How to get an endless cycle using hashmap

Use cycling iteration: map.put(key1, value2); map.put(key2, value1); then iterate,each gets points to other's value creating a cycle.

111

Why MAP is not inherited from Collection

MAP is not a Collection because it models key-value pairs, not a sequence of elements; Collection is for single-element values, incompatible with MAP's contract.

112

Why you can not use byte [] as a key in hashmap

byte[] is unsuitable as HashMap key because arrays use reference-based equality/hashCode, not content-based; two arrays with same content have different hashes and aren't equal.

113

What tree lies in the implementation of Treeset

TreeSet uses a Red-Black tree for implementation, which maintains sorted order and provides O(log n) operations for add, remove, and search.

114

Why there are no specific implementations of the Iterator interface

Iterator is an interface, not a concrete implementation; concrete iterators are provided by specific Collection implementations to avoid tight coupling and allow different traversal strategies.

Knowing the answers is half the battle

The other half is explaining them clearly under pressure.

Try a free mock interviewarrow_forward

More Java topics