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.
Tell me about the hierarchy of collections in Java
Collection → List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue; Map hierarchy separate (HashMap, TreeMap, ConcurrentHashMap).
Collection<Integer> col = Arrays.asList(1, 2, 3);
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<String, Integer> map = new HashMap<>();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).
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
LinkedList<Integer> ll = new LinkedList<>();
ll.addFirst(1);
ll.addLast(2);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.
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
Node node = map.getNode("a");
int index = hash("a") % capacity;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.
Set<Integer> set = new HashSet<>();
Map<Integer, String> map = new HashMap<>();
set.add(1);
map.put(1, "one");
Set<Integer> mapKeys = map.keySet();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.
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
Integer val = map.get("a");
map.remove("b");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.
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"));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.
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);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.
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
Collection<Integer> values = map.values();
System.out.println(values);
System.out.println(map.keySet());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).
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.
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.
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.
What are the Java collections
Java Collections include List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue (PriorityQueue), Map (HashMap, TreeMap), and utilities like Collections class.
Is Hashmap a safe stream collection
HashMap is not thread-safe; use ConcurrentHashMap for concurrent access or Collections.synchronizedMap() for full synchronization.
What is Failfast
Fail-fast means iterators throw ConcurrentModificationException if the collection is modified during iteration; it detects concurrent modifications.
What is Deque
Deque (Double Ended Queue) allows insertion/removal at both ends; implementations include ArrayDeque and LinkedList, useful for stacks and queues.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
What restriction is to add to Treeset
Elements must be Comparable (implement Comparator) or natural ordering fails; TreeSet cannot store non-comparable objects.
Can Treeset store null
No, TreeSet doesn't allow null values; throws NullPointerException due to compareTo() null checks in ordering.
What are the main implementations about the collection
List (ArrayList, LinkedList), Set (HashSet, TreeSet), Map (HashMap, TreeMap); Queue and Deque are specialized subtypes.
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.
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.
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.
What will be the search speed in linkedlist
O(n) linear search; LinkedList lacks random access, requires traversal from head or tail.
What is the search speed in Arraylist
O(1) average case for search via contains(); O(n) worst case; backed by HashMap internally.
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.
What to have inside Hashset and Treeset
HashSet: Object instances with hashCode/equals; TreeSet: Comparable/Comparator objects for sorted ordering.
LinkedList single -legged or two -link
Java LinkedList is doubly-linked; maintains previous and next node references for bidirectional traversal.
Tell me about LinkedHashmap
LinkedHashMap maintains insertion order via doubly-linked list; extends HashMap with predictable iteration order.
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.
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.
Give examples of iterators realizing Fail-Safe behavior
CopyOnWriteArrayList and CopyOnWriteArraySet use fail-safe iteration by creating snapshots, avoiding ConcurrentModificationException during concurrent modifications.
How the enumeration and iterator differ
Enumeration is legacy, unidirectional (hasMoreElements/nextElement), doesn't support removal; Iterator is newer, bidirectional with remove(), and preferred.
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.
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.
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.
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.
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.
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.
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.
Which collection implements FIFO service discipline
Queue implements FIFO (First-In-First-Out) discipline via offer/poll operations.
Which collection implements the discipline of Filo service
Stack implements LIFO (Last-In-First-Out) discipline, or use Deque with push/pop methods.
Why added ArrayList if there was already Vector
ArrayList is unsynchronized and faster than the legacy synchronized Vector; Vector is now obsolete.
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).
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
Who expands whom: Queue expands Deque, or Deque expands Queue
Deque expands Queue; Queue is a single-ended interface, Deque adds bidirectional access.
Why is LinkedList implement both List and Deque
LinkedList implements both because it efficiently supports both sequential (List) and bidirectional (Deque) operations without overhead.
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.
Which allows you to make priorityqueue
Comparator interface allows you to define custom ordering for PriorityQueue elements.
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.
What is Identityhashmap for
IdentityHashMap uses reference equality (==) instead of equals() for key comparison, useful for identity-based lookups.
What is the difference between Hashmap and IdentityHamap
HashMap uses equals() and hashCode() for equality; IdentityHashMap uses == for reference comparison only.
Why is Weakhashmap used
WeakHashMap uses weak references for keys, allowing garbage collection when keys are no longer referenced elsewhere.
What is the difference between Hashmap and Weakhashmap
HashMap keeps strong references to keys; WeakHashMap uses WeakReference, enabling automatic removal of unreachable keys.
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().
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.
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.
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.
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.
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.
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+).
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.
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.
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.
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.
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.
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.
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()).
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.
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.
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()).
How can synchronized objects of standard collections be obtained
Use Collections.synchronizedList(), Collections.synchronizedSet(), Collections.synchronizedMap() which return synchronized wrapper collections.
How to get a collection only for reading
Use Collections.unmodifiableList(), Collections.unmodifiableSet(), Collections.unmodifiableMap() to get read-only collection views.
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.
How to convert Hashset to Arraylist one line with one line
Use new ArrayList<>(hashset) or hashset.stream().collect(Collectors.toList()).
How to convert Arraylist into Hashset one line with one line
Use new HashSet<>(arraylist) or arraylist.stream().collect(Collectors.toSet()).
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.
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.
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.
What are the main SET implementation
Main SET implementations: HashSet (hash-based), TreeSet (sorted/balanced tree), LinkedHashSet (insertion-order), EnumSet (bit-vector for enums).
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).
Copyonwrite collection
CopyOnWriteArrayList/Set creates a copy of underlying array on modification, making reads fast but writes expensive; ideal for read-heavy concurrent scenarios.
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.
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.
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.
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.
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