Java Collection Flashcards

(469 cards)

1
Q

When overriding a method, can a child class throw an additional exception not declared by the parent?

A

Yes - but only if the additional exception is unchecked (i.e., a subclass of RuntimeException).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an unchecked exception in Java?

A

An exception that extends RuntimeException or Error. It does not need to be declared with throws and is not checked by the compiler at compile time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a checked exception in Java?

A

An exception that extends Exception (but not RuntimeException). It must be declared in the method signature with throws or handled with try-catch.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can a child class add a new checked exception when overriding a parent method?

A

No. A child cannot throw a new or broader checked exception that the parent method does not already declare.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can a child class throw a narrower checked exception than the parent?

A

Yes. The child can throw the same checked exception or a subclass of it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can a child class remove a checked exception entirely when overriding?

A

Yes. The child is free to not declare any checked exception, even if the parent does.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can a child class add RuntimeException even if the parent method throws nothing?

A

Yes. Unchecked exceptions can always be added or removed freely, regardless of what the parent declares.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why can a child freely add unchecked exceptions?

A

Because unchecked exceptions are not part of the method contract. Callers are not required to handle them, so they do not break the parent’s API.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why can’t a child add new checked exceptions?

A

Because callers that reference the parent type are only prepared to handle what the parent declares. Adding a new checked exception would break polymorphism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What principle does this rule protect?

A

The Liskov Substitution Principle (LSP) - a child class must be safely substitutable for its parent without breaking existing code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does the compiler do if you try to add a broader checked exception in an override?

A

It produces a compile-time error: Exception X is not compatible with throws clause in Parent.method().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

VALID or INVALID? Parent: void save() throws IOException; Child: void save() throws FileNotFoundException;

A

VALID - FileNotFoundException is a subclass of IOException (narrower checked exception).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

VALID or INVALID? Parent: void save() throws IOException; Child: void save() throws Exception;

A

INVALID - Exception is broader than IOException. The compiler will reject this.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

VALID or INVALID? Parent: void save(); Child: void save() throws NullPointerException;

A

VALID - NullPointerException is unchecked. Unchecked exceptions can always be added freely.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

VALID or INVALID? Parent: void save() throws IOException; Child: void save();

A

VALID - The child is allowed to remove the checked exception entirely.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Do these override exception rules apply to unchecked exceptions?

A

No. These rules only govern checked exceptions. Unchecked exceptions are unrestricted in overrides.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Do these rules apply to static methods?

A

No. Static methods cannot be overridden - they are hidden. The override exception rules do not apply.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Does the compiler enforce override exception rules?

A

Yes. Violations of checked exception rules in method overrides are caught at compile time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the key rule to remember for exception handling in method overrides?

A

A child method can throw the same, narrower, or no checked exceptions - and any unchecked exceptions freely. It cannot throw new or broader checked exceptions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the main benefits of the Java Collections Framework?

A

Reusability - Quality - Speed - Maintenance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does Reusability mean in the context of the Collections Framework?

A

The framework provides common classes and utility methods that work across different collection types so developers reuse proven code instead of writing their own from scratch

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does Quality mean in the context of the Collections Framework?

A

Collections Framework code is battle-tested and used by millions of developers worldwide meaning it is reliable and far less likely to contain bugs than custom-written alternatives

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How does the Collections Framework improve development Speed?

A

Developers can focus on core business logic instead of writing low-level data structure code which significantly increases productivity and shortens development time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How does the Collections Framework help with Maintenance?

A

The framework is open source with widely available API documentation making it easy for any developer to read understand and maintain code written by someone else

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What problem does Reusability in the Collections Framework solve?
It eliminates the need to reinvent the wheel - common operations like sorting and searching are already implemented and ready to use
26
Why is the Quality of Collections Framework code considered high?
It has been written reviewed tested and refined over many years by the Java community and used in production systems across the world
27
Can a developer write their own class and still benefit from Collections Framework utilities?
Yes - any class that implements a standard Collection interface such as List or Set can use utility methods in the Collections class like sort() and binarySearch()
28
What would Java development look like without the Collections Framework?
Developers would need to write and test their own data structures such as linked lists and hash tables for every project leading to inconsistent and harder-to-maintain code
29
Name the four core benefits of the Java Collections Framework.
1) Reusability 2) Quality 3) Speed 4) Maintenance
30
What is the root interface of the Collection hierarchy in Java?
The Collection interface is the root of the Java Collections Framework hierarchy
31
Does Collection extend any other interface?
Yes - Collection extends the Iterable interface
32
Why do some people consider Iterable as the root interface?
Because Collection extends Iterable making Iterable higher in the hierarchy
33
Why is Collection considered the true root and not Iterable?
Because Oracle Java API docs explicitly state that Collection is a member of the Java Collections Framework while Iterable is not
34
What package is the Collection interface in?
java.util
35
What package is the Iterable interface in?
java.lang
36
Is Iterable part of the Java Collections Framework?
No - Iterable is not stated as part of the Java Collections Framework in the official Java docs
37
Is Collection part of the Java Collections Framework?
Yes - Oracle Java API docs explicitly mention Collection as a member of the Java Collections Framework
38
What is the difference in package location between Collection and Iterable?
Collection is in java.util while Iterable is in java.lang
39
What does the Iterable interface enable?
It allows an object to be the target of a for-each loop by requiring implementation of the iterator() method
40
What is the correct answer when asked for the root of the Collections Framework hierarchy in an interview?
Collection interface - because Oracle docs define it as the root of the Collections Framework even though it extends Iterable
41
Is Collection an interface or a class?
Collection is an interface in Java
42
Is Collections an interface or a class?
Collections is a class in Java
43
What is the role of Collection in Java?
Collection is a base interface that defines methods for data structures that hold and manage objects
44
What is the role of Collections in Java?
Collections is a utility class that provides static methods for operations on Collection objects such as sorting searching and reversing
45
What is the key structural difference between Collection and Collections?
Collection is an interface that is implemented by classes. Collections is a utility class that cannot be instantiated and only provides static helper methods
46
Can you instantiate Collections?
No - Collections is a utility class with a private constructor. It is only used by calling its static methods directly
47
Give an example of a method defined in the Collection interface.
add() - remove() - size() - contains() - iterator() - these are methods that all Collection types must implement
48
Give an example of a method defined in the Collections utility class.
Collections.sort() - Collections.reverse() - Collections.shuffle() - Collections.min() - Collections.max()
49
What package is Collection in?
java.util
50
What package is Collections in?
java.util
51
Which came first - Collection or Collections?
Collection came first as the base interface. Collections was added later as a utility class to provide helper methods for working with Collection objects
52
What is the one-line interview answer for the difference between Collection and Collections?
Collection is a base interface defining the structure of data containers. Collections is a utility class providing static methods to operate on them
53
What are the Thread-safe classes in Java Collections framework?
Stack - Properties - Vector - Hashtable - BlockingQueue - ConcurrentMap - ConcurrentNavigableMap
54
Why are some Collection classes Thread-safe and others not?
Thread-safe classes use synchronization internally so only one thread can access them at a time. Non-thread-safe classes skip this overhead for better single-thread performance
55
Which thread-safe collection classes are considered legacy?
Stack - Vector and Hashtable are considered legacy thread-safe classes. Newer alternatives like ConcurrentHashMap and CopyOnWriteArrayList are preferred
56
What is the modern alternative to Hashtable?
ConcurrentHashMap - it is thread-safe like Hashtable but uses finer-grained locking so it performs much better under high concurrency
57
What is the modern alternative to Vector?
CopyOnWriteArrayList - it is thread-safe and better suited for scenarios where reads are frequent and writes are rare
58
MEMORY BOOSTER: Thread-safe Collections
Acronym SPVHBCCn - Stack - Properties - Vector - Hashtable - BlockingQueue - ConcurrentMap - ConcurrentNavigableMap. Legacy trio to avoid: Stack - Vector - Hashtable
59
How will you efficiently remove elements while iterating a Collection?
Use ListIterator.remove() method. This is safe because ListIterator is designed to modify the list during traversal
60
What exception is thrown if you use Iterator and modify a collection at the same time?
ConcurrentModificationException - thrown when a thread tries to modify a collection while another thread is iterating it
61
Why does calling remove() directly on a collection during iteration cause ConcurrentModificationException?
Because an iterator is traversing the list at the same time the list structure is being changed - Java does not allow this
62
What is the correct pattern to remove elements during List iteration?
Create a ListIterator then call iter.next() followed by iter.remove() inside a while(iter.hasNext()) loop
63
What does ListIterator provide that a regular Iterator does not?
ListIterator provides the ability to add - remove and set elements during traversal - and it can traverse in both forward and backward directions
64
MEMORY BOOSTER: Safe removal during iteration
Rule: Never call collection.remove() inside an iterator loop. Always use iterator.remove() or ListIterator.remove() to avoid ConcurrentModificationException
65
How will you convert a List to an array of primitive integers int[]?
Option 1: Use ArrayUtils.toPrimitive() from Apache Commons Lang. Option 2: Use a for loop to manually copy each element
66
What does List.toArray() return when converting a List of integers?
It returns Integer[] (an array of wrapper objects) not int[] (primitive array). Extra conversion is needed to get int[]
67
What is the Apache Commons method to convert List to int[]?
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[0]))
68
How do you convert List to int[] without any library?
Create int[] of same size as list then loop through the list and assign each value: intArray[i] = myList.get(i)
69
MEMORY BOOSTER: List to int[]
List.toArray() gives Integer[] not int[]. To get primitive int[] use ArrayUtils.toPrimitive() or a manual for loop
70
How will you convert an array of primitive integers int[] to a List?
Option 1: Use ArrayUtils.toObject() from Apache Commons then wrap with Arrays.asList(). Option 2: Use a for loop to add each element manually
71
What is the Apache Commons method to convert int[] to List?
List intList = Arrays.asList(ArrayUtils.toObject(intArray))
72
Why can you not use Arrays.asList() directly on a primitive int[] array?
Because Arrays.asList() works with objects not primitives. int[] is not an array of Integer objects so it cannot be used directly
73
How do you convert int[] to List using a for loop?
Create a new ArrayList then iterate over int[] and call intList.add(i) for each element
74
MEMORY BOOSTER: int[] to List
Primitives need boxing first. Use ArrayUtils.toObject() to box int[] to Integer[] then Arrays.asList() to wrap it into a List
75
How will you run a filter on a Collection in Java?
Option 1: Use CollectionUtils.filter() from Apache Commons with a Predicate. Option 2: Use Google Guava. Option 3: Use Java 8 Stream with Predicate
76
What is a Predicate in the context of filtering a Collection?
A Predicate is a functional interface that defines a condition. It evaluates each element and returns true if the element should be kept and false if it should be removed
77
How do you filter a Collection using Java 8 Streams?
Use stream().filter(predicate).collect(Collectors.toList()) to return a new filtered List
78
What does CollectionUtils.filter() do to the original collection?
It modifies the original collection in place - removing elements that do not match the Predicate. It does not return a new collection
79
What is the difference between filtering with Apache CollectionUtils versus Java 8 Streams?
CollectionUtils.filter() modifies the original collection. Java 8 Streams filter() creates a new collection and leaves the original unchanged
80
MEMORY BOOSTER: Filtering a Collection
Three ways to filter - Apache CollectionUtils (modifies in place) - Google Guava - Java 8 Stream filter (returns new collection). Java 8 is the modern preferred approach
81
How will you convert a List to a Set in Java?
Option 1: new HashSet<>(myList) for unordered deduplication. Option 2: new TreeSet<>(myComparator) then addAll(myList) for custom-ordered deduplication
82
What happens to duplicate elements when you convert a List to a HashSet?
Duplicate elements are automatically removed because HashSet uses hashCode() and equals() internally to detect and discard duplicates
83
When would you use TreeSet instead of HashSet to convert a List?
Use TreeSet when you need elements sorted in a custom order. You provide a Comparator to TreeSet to define how duplicates and ordering are determined
84
What method does HashSet use internally to identify duplicate elements?
hashCode() to find the bucket and equals() to confirm whether two elements are truly equal
85
MEMORY BOOSTER: List to Set
HashSet = fast + unordered + removes duplicates via hashCode/equals. TreeSet = sorted + removes duplicates via Comparator. Both eliminate duplicates automatically
86
How will you remove duplicate elements from an ArrayList in Java?
Option 1: Put elements into a HashSet then add back to ArrayList if order does not matter. Option 2: Use LinkedHashSet if insertion order must be preserved
87
Why does putting an ArrayList into a HashSet remove duplicates?
Because HashSet does not allow duplicate elements. When you add elements to a HashSet duplicates are automatically discarded
88
What is the difference between using HashSet versus LinkedHashSet to remove duplicates?
HashSet removes duplicates but does not preserve insertion order. LinkedHashSet removes duplicates and preserves the original insertion order
89
What are the steps to remove duplicates from ArrayList using HashSet?
1) Create HashSet from ArrayList 2) Call myList.clear() 3) Call myList.addAll(mySet)
90
MEMORY BOOSTER: Remove duplicates from ArrayList
Key trick - route through a Set. HashSet if order does not matter. LinkedHashSet if order matters. Both automatically eliminate duplicates
91
How can you maintain a Collection with elements in sorted order in Java?
Use TreeSet for natural ordering - PriorityQueue for ordered retrieval - Collections.sort() for one-time sorting - or implement Comparable/Comparator for custom ordering
92
What interface must a class implement to support natural ordering in a TreeSet?
Comparable interface - specifically the compareTo() method which defines the natural ordering of objects
93
What is the difference between PriorityQueue and Collections.sort() for maintaining order?
PriorityQueue maintains order at all times but only allows access to the head element. Collections.sort() sorts once at O(n log n) but allows random access
94
When would you use TreeSet over PriorityQueue?
Use TreeSet when you need a sorted collection with no duplicates and require random access to elements. Use PriorityQueue when you only need to repeatedly retrieve the smallest or largest element
95
What is the performance of Collections.sort()?
O(n log n) - it is efficient for a one-time sort but costly if called repeatedly on an updating collection
96
What is the limitation of PriorityQueue for sorted access?
You can only retrieve the head element (smallest by default). You cannot access elements at arbitrary positions like you can with a List or TreeSet
97
MEMORY BOOSTER: Sorted Collections
TreeSet = always sorted + no duplicates. PriorityQueue = always sorted + only head access. Collections.sort() = one-time sort. Comparable = natural order. Comparator = custom order
98
What are the differences between a Vector and an ArrayList in Java?
Vector is synchronized and legacy. ArrayList is not synchronized and modern. ArrayList grows by 50% when full. Vector doubles in size. ArrayList is faster for single-threaded use
99
Is ArrayList synchronized?
No - ArrayList is not synchronized. It is not thread-safe by default. Use Collections.synchronizedList() or CopyOnWriteArrayList for thread-safe alternatives
100
Is Vector synchronized?
Yes - Vector is synchronized. Every method is thread-safe but this comes at a performance cost making it slower than ArrayList in single-threaded scenarios
101
How does ArrayList resize itself when it runs out of space?
ArrayList increases its internal array size by 50% of the current size when it becomes full
102
How does Vector resize itself when it runs out of space?
Vector doubles its internal array size when it becomes full
103
Why is ArrayList preferred over Vector in modern Java?
ArrayList is faster because it is not synchronized. For thread safety there are better modern alternatives like CopyOnWriteArrayList. Vector is considered a legacy class
104
MEMORY BOOSTER: Vector vs ArrayList
ArrayList = modern + fast + not synchronized + grows by 50%. Vector = legacy + slow + synchronized + doubles in size. For thread safety use CopyOnWriteArrayList not Vector
105
What are the main differences between Collection and Collections in Java?
Collection is an interface. Collections is a utility class. Collection defines data structure methods. Collections provides static utility methods like sort() and synchronize()
106
What kind of methods does the Collection interface define?
Instance-level methods that all collection types must implement such as add() - remove() - size() - contains() and iterator()
107
What kind of methods does the Collections class provide?
Mainly static utility methods that operate on Collection instances such as sort() - reverse() - shuffle() - synchronizedList() and unmodifiableList()
108
Can you subclass or instantiate the Collections utility class?
No - Collections has a private constructor and is not meant to be instantiated or subclassed. You only ever call its static methods
109
MEMORY BOOSTER: Collection vs Collections
Collection = interface = defines WHAT a collection must do. Collections = utility class = defines HOW to operate on a collection. One letter S makes all the difference
110
In which scenario is LinkedList better than ArrayList in Java?
LinkedList is better when you do not need random access to elements and when there are frequent insertions or deletions especially in the middle or at the ends of the list
111
Why is ArrayList better for random access than LinkedList?
ArrayList uses an index-based array internally so accessing any element is O(1). LinkedList must traverse nodes from the start making access O(n)
112
Why is LinkedList better for frequent insertions and deletions?
LinkedList only needs to update node pointers for insertion or deletion which is O(1). ArrayList may need to shift all subsequent elements which is O(n)
113
What is the time complexity of inserting at the middle of an ArrayList vs LinkedList?
ArrayList: O(n) because elements must be shifted. LinkedList: O(1) for the pointer update but O(n) to find the position first
114
MEMORY BOOSTER: When to use LinkedList vs ArrayList
ArrayList = fast reads + random access + wastes time on insert/delete. LinkedList = fast insert/delete + slow random access. If you mostly read use ArrayList. If you mostly insert/delete use LinkedList
115
What are the main differences between a List and a Set in Java?
List is ordered and allows duplicates and positional access. Set is unordered and only allows unique elements with no positional access
116
Does a List allow duplicate elements?
Yes - a List allows duplicate elements and maintains the insertion order of all elements including duplicates
117
Does a Set allow duplicate elements?
No - a Set only stores unique elements. Duplicates are automatically discarded when added
118
Can you insert an element at a specific position in a Set?
No - a Set has no concept of positional order so you cannot insert at a specific index. You simply add elements and the Set manages its own internal structure
119
When would you choose a Set over a List?
When uniqueness of elements is required and order or positional access does not matter
120
MEMORY BOOSTER: List vs Set
List = ordered + duplicates allowed + positional access. Set = unordered + unique elements only + no positional access. Think of List as a numbered queue and Set as a bag of unique items
121
What are the main differences between a HashSet and a TreeSet in Java?
HashSet is unordered and faster at O(1). TreeSet is sorted in natural order and slower at O(log n). HashSet allows one null. TreeSet does not allow null
122
What is the time complexity of add() and contains() in a HashSet?
O(1) constant time - HashSet uses hashing internally for fast operations
123
What is the time complexity of add() and contains() in a TreeSet?
O(log n) - TreeSet uses a Red-Black tree internally which requires comparison at each level
124
Does HashSet allow null values?
Yes - HashSet allows exactly one null element
125
Does TreeSet allow null values?
No - TreeSet does not allow null because it uses compareTo() for ordering and calling compareTo() on null throws a NullPointerException
126
What data structure backs a HashSet internally?
A HashMap backs a HashSet internally
127
What data structure backs a TreeSet internally?
A NavigableMap (specifically a TreeMap) backs a TreeSet internally
128
What method does HashSet use for element comparison?
equals() method combined with hashCode()
129
What method does TreeSet use for element comparison?
compareTo() method from the Comparable interface or a provided Comparator
130
Name some methods available in TreeSet but not in HashSet.
pollFirst() - pollLast() - first() - last() - ceiling() - floor() - lower() - higher()
131
MEMORY BOOSTER: HashSet vs TreeSet
HashSet = Hash + fast O(1) + unordered + one null allowed. TreeSet = Tree + slower O(log n) + sorted + no null. Need speed? HashSet. Need order? TreeSet
132
When should you use a List collection in Java?
Use a List when you need ordered elements - allow duplicates - or require frequent index-based access to elements
133
When should you use a Set collection in Java?
Use a Set when you need to ensure all elements are unique and order or positional access does not matter
134
When should you use a Map collection in Java?
Use a Map when you need to store and retrieve data using key-value pairs and require fast lookup by key
135
Which collection would you use for fast key-value search?
HashMap - it provides O(1) average time for get() and put() operations using hashing
136
Which collection would you use to maintain elements in sorted order with no duplicates?
TreeSet - it stores elements in natural sorted order and does not allow duplicates
137
Which collection would you use to maintain insertion order with fast index access?
ArrayList - it preserves insertion order and provides O(1) random access by index
138
MEMORY BOOSTER: List vs Set vs Map decision guide
Duplicates needed? Use List. Unique elements only? Use Set. Key-value lookup? Use Map. Need sorted order? Use TreeSet or TreeMap. Need insertion order? Use LinkedHashSet or LinkedHashMap
139
What are the main differences between a HashMap and a Hashtable in Java?
HashMap is not synchronized and allows one null key. Hashtable is synchronized and does not allow null keys or null values. HashMap is faster for single-threaded use
140
Is HashMap thread-safe?
No - HashMap is not synchronized and not thread-safe. Use ConcurrentHashMap for a thread-safe alternative
141
Is Hashtable thread-safe?
Yes - Hashtable is fully synchronized. Only one thread can access it at a time but this makes it slower than HashMap
142
Does HashMap allow null keys?
Yes - HashMap allows exactly one null key and any number of null values
143
Does Hashtable allow null keys or null values?
No - Hashtable does not allow null keys or null values. It throws NullPointerException if you try
144
Does HashMap maintain insertion order?
Not by default. LinkedHashMap maintains insertion order. TreeMap sorts by key. A plain HashMap provides no order guarantee
145
Is Hashtable considered a legacy class?
Yes - Hashtable predates the Collections Framework. ConcurrentHashMap is the modern thread-safe alternative
146
What is the difference in Iterator behavior between HashMap and Hashtable?
HashMap Iterator is fail-fast and throws ConcurrentModificationException if the map is modified during iteration. Hashtable Enumerator is not fail-fast
147
MEMORY BOOSTER: HashMap vs Hashtable
HashMap = modern + fast + not synchronized + one null key allowed. Hashtable = legacy + slow + synchronized + no nulls. For thread safety today use ConcurrentHashMap not Hashtable
148
What are the main differences between a HashMap and a TreeMap in Java?
HashMap is unordered and O(1). TreeMap is sorted by key in natural order and O(log n). HashMap allows one null key. TreeMap does not allow null keys
149
Does HashMap maintain any order of its keys?
No - HashMap provides no guarantee about the order of its keys
150
How does TreeMap store its elements?
TreeMap stores entries sorted by natural ordering of keys using compareTo() or a provided Comparator
151
What is the internal data structure of a HashMap?
HashMap uses a Hash Table internally
152
What is the internal data structure of a TreeMap?
TreeMap uses a Red-Black Tree internally
153
What interface does HashMap implement?
HashMap implements the Map interface
154
What interface does TreeMap implement?
TreeMap implements the NavigableMap interface which extends SortedMap which extends Map
155
Does TreeMap allow null keys?
No - TreeMap does not allow null keys because it uses compareTo() and calling compareTo() on null throws NullPointerException
156
Name some methods available in TreeMap but not HashMap.
pollFirstEntry() - pollLastEntry() - tailMap() - headMap() - firstKey() - lastKey() - floorKey() - ceilingKey()
157
MEMORY BOOSTER: HashMap vs TreeMap
HashMap = Hash + O(1) + unordered + one null key. TreeMap = Red-Black Tree + O(log n) + sorted by key + no null key. Need speed? HashMap. Need sorted keys? TreeMap
158
What are the main differences between Comparable and Comparator in Java?
Comparable defines natural ordering inside the class using compareTo(). Comparator defines custom ordering outside the class using compare(). Comparable allows one sort order. Comparator allows multiple
159
What method does the Comparable interface define?
public int compareTo(Object o) - returns negative if this object is less than o - zero if equal - positive if greater
160
What method does the Comparator interface define?
public int compare(Object o1 - Object o2) - returns negative if o1 is less than o2 - zero if equal - positive if greater
161
Can a class have multiple Comparable implementations?
No - a class can only implement Comparable once defining one natural ordering. Use Comparator to define additional sort sequences
162
What package is Comparable in?
java.lang
163
What package is Comparator in?
java.util
164
When would you use Comparator over Comparable?
When you need multiple different sort orders for the same class or when you cannot modify the class source code to implement Comparable
165
What does compareTo() compare?
It compares 'this' object with the object passed as a parameter
166
What does compare() compare?
It compares two objects passed as parameters o1 and o2
167
MEMORY BOOSTER: Comparable vs Comparator
Comparable = inside the class = one sort order = compareTo(this vs other). Comparator = outside the class = multiple sort orders = compare(o1 vs o2). Remember: Comparable is natural. Comparator is custom
168
What is the purpose of a Properties file in Java?
A Properties file stores key-value pairs used for configuration - initial data or application options. It is parsed by java.util.Properties and changes to it do not require recompilation
169
What file extension do Java Properties files typically use?
.properties - for example myapp.properties
170
What class is used to parse a Properties file in Java?
java.util.Properties
171
What is a key benefit of using a Properties file over hardcoded values?
Values can be changed at runtime without recompiling the application - making configuration more flexible and maintainable
172
What are common uses of Properties files in Java applications?
Storing database configuration - application settings - environment-specific values - initial data and internationalization strings
173
MEMORY BOOSTER: Properties file
Properties file = key-value config file parsed by java.util.Properties. Extension is .properties. No recompile needed when values change. Think of it as the settings file of a Java application
174
What is the reason for overriding the equals() method in Java?
To define custom equality logic between objects. By default equals() compares memory references. Overriding it lets you compare objects by their actual field values
175
What does the default equals() method in Object class do?
It checks whether two references point to the exact same object in memory (reference equality) using ==
176
Give an example of when you would override equals().
A Person class with firstName - lastName and age fields. You override equals() so two Person objects with the same name and age are considered equal even if they are different instances
177
When is overriding equals() especially important in Java Collections?
When using an object as a key in a HashMap or storing objects in a HashSet - because these collections use equals() to check for duplicate keys or elements
178
What is the contract rule when overriding equals()?
If you override equals() you must also override hashCode() - two objects that are equal via equals() must return the same hashCode()
179
MEMORY BOOSTER: equals() override
Default equals() = reference comparison (same object in memory). Overridden equals() = value comparison (same field values). Always override hashCode() together with equals() or HashMap and HashSet will break
180
How does the hashCode() method work in Java?
hashCode() returns an integer hash value for an object. By default it is based on the object's memory address. If two objects are equal via equals() they must return the same hashCode
181
Is hashCode() a pure Java method?
No - hashCode() in the Object class is a native method. Its default implementation is not written in pure Java and relies on the JVM
182
What is the contract between hashCode() and equals()?
If two objects are equal according to equals() they must have the same hashCode(). However two objects with the same hashCode() are not necessarily equal
183
Why is it important to override hashCode() when you override equals()?
Because HashMap and HashSet use hashCode() to find the right bucket and then equals() to confirm equality. If hashCode() is inconsistent with equals() these collections will behave incorrectly
184
What happens if two unequal objects return the same hashCode?
This is called a hash collision. It is allowed but reduces performance because multiple entries end up in the same bucket and require equals() to distinguish them
185
MEMORY BOOSTER: hashCode()
hashCode() = integer fingerprint of an object. Default is memory-address-based. Override it whenever you override equals(). Same equals() must mean same hashCode(). Different hashCode means definitely not equal
186
Is it a good idea to use Generics in Collections?
Yes - Generics make Collections type-safe by restricting the type of elements they can hold. This catches type errors at compile time instead of runtime and eliminates the need for casting
187
What is the main benefit of using Generics in a Collection?
Type safety - the compiler checks that only the correct type of element is added and retrieved. This eliminates ClassCastException at runtime
188
What problem does using a raw Collection without Generics cause?
Without Generics a Collection can hold any Object. Type casting is required on retrieval and errors only appear at runtime as ClassCastException
189
Give an example of a generic Collection declaration.
List names = new ArrayList() - this list can only hold String objects and no casting is needed when retrieving elements
190
MEMORY BOOSTER: Generics in Collections
Generics = type safety at compile time. No Generics = ClassCastException risk at runtime. Always use Generics in Collections. The in List means only T type elements are allowed
191
What is the difference between Collections.emptyList() and creating a new instance of a Collection?
Both return an empty list but Collections.emptyList() returns an immutable singleton instance that is reused. A new instance is mutable and a fresh object each time
192
Is Collections.emptyList() mutable?
No - Collections.emptyList() returns an immutable list. You cannot add - remove or modify elements in it
193
What design pattern does Collections.emptyList() follow?
Singleton pattern - it always returns the same shared instance of an empty list rather than creating a new object each time
194
When should you use Collections.emptyList() over new ArrayList<>()?
Use Collections.emptyList() when you need a read-only empty list and may call it multiple times. It avoids unnecessary object creation and improves performance
195
What happens if you try to add an element to Collections.emptyList()?
It throws UnsupportedOperationException because the list is immutable
196
MEMORY BOOSTER: emptyList() vs new ArrayList<>()
Collections.emptyList() = immutable + singleton + no object creation + fast. new ArrayList<>() = mutable + new object every time. Use emptyList() for read-only empty lists. Use new ArrayList<>() when you need to add elements
197
How will you copy elements from a source List to another List in Java?
Option 1: Use the ArrayList constructor - new ArrayList<>(sourceList). Option 2: Use Collections.copy() where the destination must be the same size or larger than the source
198
What is the difference between the ArrayList copy constructor and Collections.copy()?
The constructor allocates new memory and copies elements. Collections.copy() copies into an existing list of sufficient size without reallocating memory
199
What exception does Collections.copy() throw if the destination is too small?
IndexOutOfBoundsException - Collections.copy() does not resize the destination list. It requires the destination to already be large enough
200
What is the time complexity guarantee of Collections.copy()?
Collections.copy() guarantees linear time O(n) performance for the copy operation
201
What is a limitation of Collections.copy()?
It only accepts List as both source and destination. It cannot copy from or to other Collection types like Set or Queue
202
When is Collections.copy() preferred over the constructor approach?
When you want to reuse an existing array or pre-allocated list rather than allocating new memory - for example in memory-sensitive or performance-critical scenarios
203
MEMORY BOOSTER: Copying a List
Constructor copy = simple + new memory allocated. Collections.copy() = reuses existing list + linear time guaranteed + destination must be pre-sized. Remember: Collections.copy() throws IndexOutOfBoundsException if destination is too small
204
What are the Java Collection classes that implement the List interface?
AbstractList - AbstractSequentialList - ArrayList - AttributeList - CopyOnWriteArrayList - LinkedList - RoleList - RoleUnresolvedList - Stack - Vector
205
Which List implementation is best for general-purpose use?
ArrayList - it provides fast random access O(1) and is the most commonly used List implementation
206
Which List implementation is thread-safe and suitable for read-heavy concurrent use?
CopyOnWriteArrayList - it creates a fresh copy of the underlying array on every write making reads very fast and thread-safe
207
Which List implementations are considered legacy?
Stack and Vector are legacy List implementations. Prefer Deque over Stack and ArrayList or CopyOnWriteArrayList over Vector
208
MEMORY BOOSTER: List implementations
Common ones to know: ArrayList (general use) - LinkedList (frequent insert/delete) - CopyOnWriteArrayList (concurrent reads) - Stack and Vector (legacy - avoid). All implement the List interface
209
What are the Java Collection classes that implement the Set interface?
AbstractSet - ConcurrentSkipListSet - CopyOnWriteArraySet - EnumSet - HashSet - JobStateReasons - LinkedHashSet - TreeSet
210
Which Set implementation maintains insertion order?
LinkedHashSet - it maintains the order in which elements were inserted while still enforcing uniqueness
211
Which Set implementation is best for storing enum constants?
EnumSet - it is highly optimized for use with enum types and is the fastest Set implementation for enums
212
Which Set implementation is thread-safe?
ConcurrentSkipListSet and CopyOnWriteArraySet are thread-safe Set implementations
213
MEMORY BOOSTER: Set implementations
HashSet = fast + unordered. LinkedHashSet = insertion order preserved. TreeSet = sorted. EnumSet = enums only. ConcurrentSkipListSet = thread-safe + sorted. All enforce uniqueness
214
What is the difference between an Iterator and a ListIterator in Java?
Iterator traverses any Collection in one direction only. ListIterator traverses only Lists but supports bidirectional traversal and allows add - set and remove during iteration
215
Which data structures can Iterator traverse?
Iterator can traverse List - Set and Queue and any Collection that implements the Iterable interface
216
Which data structures can ListIterator traverse?
ListIterator can only traverse Lists such as ArrayList and LinkedList
217
Can Iterator traverse in reverse direction?
No - Iterator can only traverse in the forward direction
218
Can ListIterator traverse in reverse direction?
Yes - ListIterator can traverse both forward using next() and backward using previous()
219
Can you add an element to a collection while using a regular Iterator?
No - adding elements during iteration with a regular Iterator throws ConcurrentModificationException
220
Can you add an element while using a ListIterator?
Yes - ListIterator provides an add() method that safely inserts elements during traversal
221
What index methods does ListIterator provide that Iterator does not?
nextIndex() and previousIndex() to get the index of the element that would be returned by the next call to next() or previous()
222
Can you replace an element using Iterator?
No - Iterator does not provide a set() method
223
Can you replace an element using ListIterator?
Yes - ListIterator provides set(e) to replace the last element returned by next() or previous()
224
MEMORY BOOSTER: Iterator vs ListIterator
Iterator = any Collection + forward only + remove only. ListIterator = List only + bidirectional + add + remove + set + index methods. Think of ListIterator as a more powerful Iterator for Lists
225
What is the difference between Iterator and Enumeration in Java?
Enumeration is older and only works on legacy collections with no remove support. Iterator is newer - works on all collections and supports removal. Iterator is fail-fast. Enumeration is not
226
Is Enumeration fail-fast?
No - Enumeration is not fail-fast. It does not throw ConcurrentModificationException if the collection is modified during traversal
227
Is Iterator fail-fast?
Yes - Iterator is fail-fast. It throws ConcurrentModificationException if the collection is modified during iteration by any thread other than the iterator itself
228
Does Enumeration support removing elements during traversal?
No - Enumeration does not have a remove() method. You cannot remove elements while using it
229
Does Iterator support removing elements during traversal?
Yes - Iterator provides a remove() method to safely remove elements during traversal
230
Which collections support Enumeration?
Only legacy collections like Vector and Hashtable support Enumeration
231
Which collections support Iterator?
All modern Collection classes support Iterator. Legacy collections also support it
232
MEMORY BOOSTER: Iterator vs Enumeration
Enumeration = old + legacy collections only + no remove + not fail-fast. Iterator = modern + all collections + has remove() + fail-fast. Always prefer Iterator over Enumeration in new code
233
What are the main differences between ArrayList and LinkedList data structures?
ArrayList is an index-based dynamic array with fast random access O(1). LinkedList is a doubly linked list with fast insertion and deletion O(1) but slow random access O(n)
234
What is the internal data structure of an ArrayList?
A dynamic array that resizes automatically when more capacity is needed
235
What is the internal data structure of a LinkedList?
A doubly linked list where each node holds a reference to the next and previous nodes
236
What is the time complexity of accessing an element by index in ArrayList vs LinkedList?
ArrayList: O(1) - direct index access. LinkedList: O(n) - must traverse from the head node
237
What is the time complexity of inserting or deleting at the middle of ArrayList vs LinkedList?
ArrayList: O(n) - elements must be shifted. LinkedList: O(n) to find position + O(1) to update pointers
238
Which uses more memory - ArrayList or LinkedList?
LinkedList uses more memory because each node stores the data plus two pointers (next and previous). ArrayList only stores the data in a compact array
239
When is LinkedList faster than ArrayList?
For insertions and deletions at the head or tail of the list - LinkedList is O(1). ArrayList is O(n) for mid-list operations due to element shifting
240
MEMORY BOOSTER: ArrayList vs LinkedList
ArrayList = array inside + fast read O(1) + slow insert/delete O(n) + less memory. LinkedList = nodes with pointers + slow read O(n) + fast insert/delete at ends O(1) + more memory. Most cases ArrayList wins
241
What are the main differences between a Set and a Map in Java?
Set stores unique single elements. Map stores unique key-value pairs. Set allows one null element. Map allows one null key but many null values. Neither guarantees order by default
242
Does a Set allow duplicate elements?
No - a Set only allows unique elements. Duplicates are discarded automatically
243
Does a Map allow duplicate keys?
No - a Map does not allow duplicate keys. If you insert a duplicate key the new value replaces the old one
244
Does a Map allow duplicate values?
Yes - a Map allows duplicate values as long as each value is associated with a different key
245
How many null elements can a Set hold?
A Set can hold at most one null element
246
How many null keys can a Map hold?
A Map (like HashMap) can hold at most one null key but can hold any number of null values
247
Does Map extend Collection?
No - Map does not extend the Collection interface. It has its own separate hierarchy in the Java Collections Framework
248
MEMORY BOOSTER: Set vs Map
Set = bag of unique items = one null allowed. Map = dictionary of key-value pairs = one null key + many null values. Set extends Collection. Map does NOT extend Collection. Both disallow duplicate keys/elements
249
What is the use of the Dictionary class in Java?
Dictionary stores key-value pairs where neither key nor value can be null. It is a legacy abstract class that has been deprecated and should not be used in new code
250
Is the Dictionary class deprecated?
Yes - Dictionary is deprecated. HashMap and ConcurrentHashMap are the modern replacements for key-value storage
251
Does Dictionary allow null keys or null values?
No - Dictionary does not allow null keys or null values
252
What replaced the Dictionary class in modern Java?
HashMap for non-thread-safe use and ConcurrentHashMap for thread-safe use
253
MEMORY BOOSTER: Dictionary class
Dictionary = legacy abstract class = key-value storage = no nulls allowed = DEPRECATED. Use HashMap instead. You may see it in legacy code but never write new code with it
254
What is the default size of load factor in a HashMap in Java?
The default load factor of a HashMap is 0.75 (75%)
255
What is the default initial capacity of a HashMap in Java?
The default initial capacity is 16 buckets
256
What is the significance of load factor in a HashMap?
Load factor determines when the HashMap should resize. When the number of entries exceeds capacity multiplied by load factor the HashMap doubles its capacity and rehashes
257
At what point does a default HashMap with capacity 16 resize?
When 12 entries are stored (16 x 0.75 = 12) the HashMap doubles its capacity from 16 to 32
258
What happens internally when a HashMap exceeds its load factor threshold?
The HashMap doubles its internal array size and rehashes all existing entries into the new larger array - this is called resizing or rehashing
259
What is the trade-off of a higher load factor in a HashMap?
A higher load factor means less memory used but more hash collisions leading to slower performance. A lower load factor means faster lookups but more memory used
260
MEMORY BOOSTER: HashMap load factor
Default capacity = 16. Default load factor = 0.75. Resize triggers at 16 x 0.75 = 12 entries. After resize capacity doubles to 32. Load factor balances memory vs performance
261
What are the major differences between a HashSet and a HashMap?
HashSet implements Set and stores only values. HashMap implements Map and stores key-value pairs. HashSet has no duplicate elements. HashMap has no duplicate keys but allows duplicate values. HashSet allows one null. HashMap allows one null key and many null values
262
What interface does HashSet implement?
HashSet implements the Set interface
263
What interface does HashMap implement?
HashMap implements the Map interface
264
Can HashSet store duplicate elements?
No - HashSet does not allow duplicate elements
265
Can HashMap store duplicate keys?
No - HashMap does not allow duplicate keys but it does allow duplicate values
266
How do you iterate over a HashMap?
A HashMap must first be converted to a Set using entrySet() or keySet() and then iterated using an Iterator or for-each loop
267
What is stored inside a HashSet element vs a HashMap entry?
A HashSet stores only single value objects. A HashMap stores entries which are key-value pairs
268
MEMORY BOOSTER: HashSet vs HashMap
HashSet = Set interface = values only = no duplicates. HashMap = Map interface = key-value pairs = no duplicate keys. Internally HashSet is backed by a HashMap - every HashSet element is stored as a key in the underlying HashMap with a dummy value
269
What are the similarities between a HashSet and a HashMap in Java?
Both are hashing-based - both are unsynchronized - both do not guarantee element order - HashSet is internally backed by a HashMap - both give constant time O(1) performance for basic operations
270
Are HashSet and HashMap thread-safe?
No - neither HashSet nor HashMap is synchronized or thread-safe by default. They must be explicitly wrapped with synchronized versions for multi-threading
271
What is the internal relationship between HashSet and HashMap?
A HashSet is internally backed by a HashMap. When you add an element to a HashSet it is stored as a key in the underlying HashMap with a constant dummy value
272
MEMORY BOOSTER: HashSet and HashMap similarities
Both Hash-based + both unordered + both not thread-safe + both O(1) performance. The biggest surprise: HashSet uses a HashMap internally. They share the same hashing engine
273
What is the reason for overriding the equals() method in Java?
To define custom equality based on field values rather than memory reference. Especially important when using an object as a key in a HashMap
274
MEMORY BOOSTER: equals() override
Default equals() checks if two references point to the same memory address. Override it to compare by value. Always override hashCode() at the same time or HashMap and HashSet will break
275
How can we synchronize the elements of a List - a Set or a Map in Java?
Use static methods from the Collections utility class: Collections.synchronizedList() - Collections.synchronizedSet() - Collections.synchronizedMap() - Collections.synchronizedSortedMap() - Collections.synchronizedSortedSet()
276
What method makes a List thread-safe in Java?
Collections.synchronizedList(List list) - returns a synchronized thread-safe list backed by the specified list
277
What method makes a Map thread-safe in Java?
Collections.synchronizedMap(Map m) - returns a synchronized thread-safe map backed by the specified map
278
What method makes a Set thread-safe in Java?
Collections.synchronizedSet(Set s) - returns a synchronized thread-safe set backed by the specified set
279
MEMORY BOOSTER: Synchronizing Collections
One pattern to remember: Collections.synchronized___() - fill in List - Set - Map - SortedMap or SortedSet. These wrap your collection in a synchronized shell. For better performance use ConcurrentHashMap or CopyOnWriteArrayList instead
280
What is a Hash Collision?
A Hash Collision occurs when two different objects produce the same hashCode. The HashMap must then handle storing both objects that map to the same bucket
281
How does Java handle hash collisions in a HashMap?
In a HashMap Java replaces the old key-value entry with the new one when a hash collision occurs for the same key. For different keys with the same hash - entries are chained in the same bucket
282
What are the Hash Collision resolution techniques?
Separate Chaining with Linked List - Separate Chaining with List Head Cells - Open Addressing with Coalesced Hashing - Open Addressing with Cuckoo Hashing - Hopscotch Hashing - Robinhood Hashing
283
MEMORY BOOSTER: Hash Collision
Hash Collision = two different objects share the same hashCode. Java's HashMap handles it by chaining entries in the same bucket. Resolution techniques: Separate Chaining and Open Addressing are the two main families
284
What is the difference between Queue and Stack data structures?
Queue is FIFO - first element added is the first removed. Stack is LIFO - last element added is the first removed. Queue processes from front. Stack processes from top
285
What does FIFO stand for and which data structure uses it?
FIFO stands for First In First Out. Queue uses FIFO ordering. Like a ticket line - the first person in is the first served
286
What does LIFO stand for and which data structure uses it?
LIFO stands for Last In First Out. Stack uses LIFO ordering. Like a browser back button - the last page visited is the first one you go back to
287
MEMORY BOOSTER: Queue vs Stack
Queue = FIFO = ticket line = first in first out. Stack = LIFO = browser back button = last in first out. Queue adds to back and removes from front. Stack adds and removes from the top
288
What is an Iterator in Java?
Iterator is an interface in java.util package used to traverse and access elements in a Collection one at a time. It is based on the Iterator design pattern
289
What package is the Iterator interface in?
java.util
290
What design pattern is Iterator based on?
The Iterator design pattern - it provides a common interface to traverse a container of objects while hiding the underlying implementation of the collection
291
MEMORY BOOSTER: Iterator
Iterator = traversal tool for any Collection. Package: java.util. Pattern: Iterator design pattern. Key methods: hasNext() - next() - remove(). Think of it as a cursor moving through a collection one element at a time
292
What is the difference between Iterator and Enumeration in Java?
Enumeration is older (JDK 1.0) and only works on legacy collections with no remove() method and is fail-safe. Iterator is newer (Java 1.2) - works on all collections - has remove() - and is fail-fast
293
What are the method names in the Iterator interface?
hasNext() - next() - remove()
294
What are the method names in the Enumeration interface?
hasMoreElements() - nextElement()
295
Is Enumeration fail-fast or fail-safe?
Fail-safe - Enumeration does not throw ConcurrentModificationException if the collection is modified during traversal
296
Is Iterator fail-fast or fail-safe?
Fail-fast - Iterator throws ConcurrentModificationException if the collection is modified by another thread during iteration
297
Which legacy classes use Enumeration?
Vector - Stack and Hashtable support Enumeration
298
Why is Iterator considered safer than Enumeration?
Because Iterator is fail-fast and immediately reports when a collection is modified during iteration - preventing data inconsistency. Enumeration silently continues which can lead to unpredictable behavior
299
MEMORY BOOSTER: Iterator vs Enumeration
Enumeration = old + legacy only + no remove() + fail-safe + longer method names. Iterator = modern + all collections + has remove() + fail-fast + shorter method names. Always prefer Iterator in new code
300
What is the design pattern used in the implementation of Enumeration in Java?
Enumeration is based on the Iterator design pattern. It provides a common interface to traverse a collection of objects while hiding the underlying implementation details
301
MEMORY BOOSTER: Enumeration design pattern
Both Iterator interface and Enumeration interface are based on the Iterator design pattern. The pattern provides a uniform way to traverse any collection regardless of its internal structure
302
Which methods must an object implement to be used as a key in a HashMap?
The object must implement both equals() and hashCode() methods correctly
303
Why does a HashMap key need both equals() and hashCode()?
hashCode() is used to find the correct bucket. equals() is used to confirm the exact key match within that bucket. Without both - HashMap cannot reliably store or retrieve key-value pairs
304
MEMORY BOOSTER: HashMap key requirements
Two methods required for a HashMap key: hashCode() to locate the bucket + equals() to find the exact match. Miss either one and your HashMap will behave incorrectly. They are always a pair
305
How will you reverse a List in Java?
Use Collections.reverse(myList) - this method from the Collections utility class reverses the order of elements in the specified List in place
306
MEMORY BOOSTER: Reverse a List
Collections.reverse(myList) - one line - in place - no new list created. Remember it is Collections (plural) not Collection
307
How will you convert an array of String objects into a List?
Use Arrays.asList(myArray) from java.util.Arrays - it accepts an array and returns a fixed-size List backed by the array
308
What is the limitation of the List returned by Arrays.asList()?
The returned List is fixed-size. You cannot add or remove elements from it. Attempting to do so throws UnsupportedOperationException. You can use new ArrayList<>(Arrays.asList(arr)) for a fully mutable list
309
MEMORY BOOSTER: Array to List
Arrays.asList(myArray) = quick conversion but fixed size. Wrap with new ArrayList<>() if you need a mutable list. Package: java.util.Arrays
310
What is the difference between peek() - poll() and remove() methods of Queue in Java?
peek() retrieves the head without removing it and returns null if empty. poll() retrieves and removes the head and returns null if empty. remove() retrieves and removes the head but throws NoSuchElementException if empty
311
What does peek() return when the Queue is empty?
null - peek() never throws an exception
312
What does poll() return when the Queue is empty?
null - poll() never throws an exception
313
What does remove() throw when the Queue is empty?
NoSuchElementException
314
MEMORY BOOSTER: peek vs poll vs remove in Queue
peek() = look only + null if empty. poll() = take + null if empty. remove() = take + exception if empty. Safe pair: peek and poll. Dangerous one: remove. Think poll = polite (returns null). remove = strict (throws exception)
315
What are the main differences between Array and ArrayList in Java?
Array is fixed size and supports primitives and is faster. ArrayList is dynamic - resizes automatically - supports only objects - uses Generics for type safety and provides Iterator support
316
Can an Array store primitive data types?
Yes - an Array can store both primitive types like int and double as well as objects
317
Can an ArrayList store primitive data types?
No - ArrayList can only store objects. Primitives must be autoboxed into wrapper types like Integer or Double
318
How do you get the size of an Array vs an ArrayList?
Array uses the length field: myArray.length. ArrayList uses the size() method: myList.size()
319
Can an Array be multi-dimensional?
Yes - Arrays can be multi-dimensional. ArrayList is always single-dimensional
320
What exception is thrown when you store a wrong type in an Array?
ArrayStoreException - thrown at runtime when you try to store an incompatible type in an array
321
MEMORY BOOSTER: Array vs ArrayList
Array = fixed size + primitives allowed + length field + faster. ArrayList = dynamic + objects only + size() method + Generics support + Iterator support. Use Array when size is known and fixed. Use ArrayList for flexibility
322
How will you insert - delete and retrieve elements from a HashMap in Java?
Insert: put(key - value). Retrieve: get(key). Delete: remove(key). All three operations are O(1) average time
323
What method retrieves a value from a HashMap?
get(Object key) - returns the value associated with the key or null if the key is not found
324
What method inserts a key-value pair into a HashMap?
put(Key k - Value v) - adds the entry and returns the previous value associated with the key or null if there was no mapping
325
What method deletes an entry from a HashMap?
remove(Object key) - removes the key-value pair and returns the value that was associated with the key
326
MEMORY BOOSTER: HashMap operations
Three core HashMap operations: get(key) = retrieve. put(key - value) = insert. remove(key) = delete. All run in O(1) average time. Easy to remember: Get - Put - Remove
327
What are the main differences between HashMap and ConcurrentHashMap in Java?
HashMap is not synchronized and allows one null key. ConcurrentHashMap is synchronized - does not allow null keys or null values - and is designed for safe multi-threaded access
328
Does ConcurrentHashMap allow null keys?
No - ConcurrentHashMap does not allow null keys or null values. This is different from HashMap which allows one null key
329
Why is ConcurrentHashMap better than HashMap in multi-threaded environments?
ConcurrentHashMap uses segment-level locking so multiple threads can read and write simultaneously without locking the entire map - giving much better concurrency than a synchronized HashMap
330
MEMORY BOOSTER: HashMap vs ConcurrentHashMap
HashMap = fast + not thread-safe + one null key allowed. ConcurrentHashMap = thread-safe + no nulls + locks only a segment not the whole map. Use ConcurrentHashMap when multiple threads access the map
331
What is the increasing order of performance for Hashtable - SynchronizedMap - ConcurrentHashMap and HashMap?
From slowest to fastest: Hashtable - then Collections.synchronizedMap - then ConcurrentHashMap - then HashMap (fastest)
332
Why is HashMap the fastest Map implementation?
HashMap has no synchronization overhead. It performs all operations without any locking making it the fastest option in single-threaded scenarios
333
Why does Hashtable have the worst performance among Map implementations?
Hashtable synchronizes every single method with a single lock on the entire map - creating maximum contention between threads
334
MEMORY BOOSTER: Map performance order
Slowest to fastest: Hashtable < SynchronizedMap < ConcurrentHashMap < HashMap. More synchronization = slower. HashMap wins because it has zero synchronization overhead
335
Why does Map interface not extend Collection interface in Java?
Because Map requires two parameters (key and value) to add an entry but Collection.add() only accepts one parameter. Map also needs specific methods like keySet() and values() that do not fit the Collection model
336
What method does Collection use to add elements?
add(Object o) - it takes only one parameter which is incompatible with Map which needs both a key and a value
337
MEMORY BOOSTER: Why Map does not extend Collection
Collection.add() takes ONE parameter. Map.put() takes TWO (key + value). The interfaces are fundamentally incompatible. Map is part of the Collections Framework but NOT a subtype of Collection
338
What are the different ways to iterate elements of a List in Java?
Option 1: Use an Iterator with hasNext() and next(). Option 2: Use a for-each loop. Option 3 (Java 8+): Use forEach() with a lambda or stream()
339
MEMORY BOOSTER: Iterating a List
Three main ways: Iterator (explicit control) - for-each loop (clean syntax) - Java 8 forEach/stream (functional style). For-each is most common for simple traversal. Iterator is needed when removing elements during traversal
340
What is CopyOnWriteArrayList and how is it different from ArrayList?
CopyOnWriteArrayList is a thread-safe List introduced in Java 5. On every write operation it creates a fresh copy of the underlying array. Its Iterator never throws ConcurrentModificationException but does not reflect changes made after the iterator was created
341
Does CopyOnWriteArrayList throw ConcurrentModificationException?
No - the Iterator of CopyOnWriteArrayList is guaranteed to never throw ConcurrentModificationException
342
When should you use CopyOnWriteArrayList?
When reads are much more frequent than writes and thread safety is required. Each write creates a full array copy so it is expensive for write-heavy workloads
343
Does CopyOnWriteArrayList allow null elements?
Yes - CopyOnWriteArrayList permits null elements
344
MEMORY BOOSTER: CopyOnWriteArrayList
CopyOnWrite = every write creates a new copy of the array. Thread-safe. No ConcurrentModificationException. Iterator shows snapshot at creation time. Best for read-heavy + write-rare concurrent scenarios
345
How is remove() method implemented in a HashMap?
First the correct bucket is located using the key hash. Then within the bucket the entry is removed like removing a node from a singly linked list by updating the next pointer of the preceding entry
346
MEMORY BOOSTER: HashMap remove() internals
remove() = find bucket via hash + unlink node from chain. If it is the first entry in bucket - set bucket head to e.next. If not - set previous.next to e.next. Same hash lookup logic as get()
347
What is a BlockingQueue in Java?
BlockingQueue extends Queue and was introduced in Java 1.5. It blocks and waits when retrieving from an empty queue or when storing into a full queue. It is thread-safe and used in producer-consumer scenarios
348
Does BlockingQueue allow null elements?
No - BlockingQueue does not accept null elements
349
What is the main use case of BlockingQueue?
Producer-consumer problems where one thread produces data and another consumes it. BlockingQueue handles the synchronization automatically
350
Is BlockingQueue thread-safe?
Yes - BlockingQueue implementations are thread-safe and can be used for inter-thread communication
351
MEMORY BOOSTER: BlockingQueue
BlockingQueue = Queue + blocking behavior + thread-safe + no nulls. Blocks on get() if empty. Blocks on put() if full. Perfect for producer-consumer problems. Introduced in Java 1.5
352
How is TreeMap implemented internally in Java?
TreeMap uses a Red-Black tree internally. It is a NavigableMap that stores keys in natural order or using a Comparator provided at creation time. TreeMap is not synchronized
353
Is TreeMap synchronized?
No - TreeMap is not synchronized. It must be wrapped with Collections.synchronizedSortedMap() for thread-safe use
354
What tree structure does TreeMap use internally?
Red-Black tree - a self-balancing binary search tree that guarantees O(log n) performance for get - put and remove operations
355
MEMORY BOOSTER: TreeMap internals
TreeMap = Red-Black tree = sorted by key = NavigableMap = not synchronized. O(log n) for all operations. Natural order by default or use a Comparator. Think of it as a self-balancing sorted dictionary
356
What is the difference between a Fail-fast and a Fail-safe iterator in Java?
Fail-fast throws ConcurrentModificationException if the collection is modified during iteration and works on the original collection. Fail-safe works on a copy of the collection and never throws ConcurrentModificationException
357
Does a Fail-fast iterator clone the collection?
No - a Fail-fast iterator works directly on the original collection and throws ConcurrentModificationException if it detects structural changes
358
Does a Fail-safe iterator clone the collection?
Yes - a Fail-safe iterator works on a copy of the original collection so changes to the original do not affect iteration
359
Give an example of a Fail-fast iterator.
The iterators of ArrayList - HashMap and HashSet are fail-fast
360
Give an example of a Fail-safe iterator.
The iterators of ConcurrentHashMap and CopyOnWriteArrayList are fail-safe
361
MEMORY BOOSTER: Fail-fast vs Fail-safe
Fail-fast = works on original + throws ConcurrentModificationException on modification. Fail-safe = works on copy + never throws exception. Fast = fragile. Safe = copy-protected. ConcurrentHashMap and CopyOnWriteArrayList use fail-safe iterators
362
How does ConcurrentHashMap work in Java?
ConcurrentHashMap extends AbstractMap and was introduced in Java 1.5. It divides the map into segments and only locks the segment being written to - allowing concurrent reads and writes across different segments
363
Are all methods of ConcurrentHashMap thread-safe?
Yes - all methods in ConcurrentHashMap are thread-safe
364
What is the key difference between ConcurrentHashMap and Hashtable locking?
Hashtable locks the entire map for every operation. ConcurrentHashMap locks only the relevant segment allowing much higher concurrency
365
MEMORY BOOSTER: ConcurrentHashMap
ConcurrentHashMap = HashMap + thread-safety + segment locking. Divides map into segments - only locks the segment being written. Much faster than Hashtable. Introduced in Java 1.5. No null keys or values allowed
366
What is the importance of hashCode() and equals() methods in a HashMap?
hashCode() locates the bucket. equals() confirms the exact key. If hashCode() always returns the same value for all keys - all entries collide into one bucket making the HashMap perform like a linked list at O(n). Incorrect implementation makes HashMap inefficient
367
What happens if two different keys always return the same hashCode in a HashMap?
All entries land in the same bucket causing maximum collisions. The HashMap degrades to O(n) performance instead of O(1) because equals() must scan through all entries in that bucket
368
MEMORY BOOSTER: hashCode() and equals() in HashMap
hashCode() = which bucket to store in. equals() = which exact entry within the bucket. Poor hashCode() = too many collisions = slow HashMap. Always implement them as a pair and follow the contract: equal objects must have equal hash codes
369
What is the contract between hashCode() and equals() in Java?
Rule 1: If object1.equals(object2) is true then object1.hashCode() must equal object2.hashCode(). Rule 2: If two objects have the same hashCode they are not necessarily equal - it could be a hash collision
370
If two objects are equal via equals() what must be true about their hashCode()?
Their hashCode() must return the same value - this is a mandatory contract in Java
371
If two objects have the same hashCode() does that mean they are equal?
No - same hashCode does not guarantee equality. It could be a hash collision. equals() must also return true for two objects to be considered equal
372
MEMORY BOOSTER: hashCode/equals contract
Equal objects MUST have equal hashCodes. Equal hashCodes do NOT mean equal objects. One-way guarantee: equals true => hashCode same. Not reversible: hashCode same does NOT mean equals true
373
What is an EnumSet in Java?
EnumSet is a specialized Set implementation designed exclusively for use with enum types. It uses a bit vector internally - is very fast - does not allow null elements and is not synchronized
374
What is the internal representation of an EnumSet?
EnumSet is represented internally as a bit vector making it extremely memory-efficient and fast for enum types
375
Does EnumSet allow null elements?
No - EnumSet throws NullPointerException if you try to insert a null element
376
Is EnumSet thread-safe?
No - EnumSet is not synchronized. It must be wrapped for thread-safe use
377
What is EnumSet a good alternative to?
EnumSet is a good alternative to int-based bit flags implementations - it is type-safe and more readable
378
MEMORY BOOSTER: EnumSet
EnumSet = Set + enums only + bit vector internally + extremely fast + no nulls + not thread-safe. Best use: when you have a Set of enum constants. Alternative to int bit flags. All elements must come from the same enum type
379
What are the main Concurrent Collection classes introduced in Java 1.5?
ArrayBlockingQueue - CopyOnWriteArrayList - CopyOnWriteArraySet - ConcurrentHashMap - ConcurrentLinkedDeque - ConcurrentLinkedQueue - LinkedBlockingQueue - LinkedBlockingDeque - PriorityBlockingQueue
380
What package contains the Concurrent Collection classes?
java.util.concurrent - introduced in Java 1.5
381
What is special about the iterators of Concurrent Collection classes?
Their iterators are fail-safe - they do not throw ConcurrentModificationException and the collection can be modified safely during iteration
382
MEMORY BOOSTER: Concurrent Collections
Package: java.util.concurrent. All fail-safe iterators. All thread-safe. Key classes: ConcurrentHashMap - CopyOnWriteArrayList - BlockingQueue variants. Introduced in Java 1.5 to replace legacy Hashtable and Vector
383
How will you convert a Collection to a SynchronizedCollection in Java?
Use Collections.synchronizedCollection(Collection c) - this static method wraps any Collection in a synchronized thread-safe wrapper
384
MEMORY BOOSTER: SynchronizedCollection
Collections.synchronizedCollection(c) = one method to wrap any Collection in thread-safety. Remember to synchronize manually on the returned collection when iterating it to avoid ConcurrentModificationException
385
How is IdentityHashMap different from a regular Map in Java?
IdentityHashMap uses reference equality (==) to compare keys instead of equals(). Two keys are equal only if they are the exact same object in memory
386
What equality check does IdentityHashMap use for keys?
Reference equality using == operator. Two keys are equal only if k1 == k2
387
What equality check does HashMap use for keys?
Value equality using equals() method: k1.equals(k2)
388
What are the main use cases of IdentityHashMap?
Topology-preserving transformations like serialization and deep-copying where the same object should not be considered equal to another even if their values match. Also used for maintaining proxy objects
389
Is IdentityHashMap thread-safe?
No - IdentityHashMap is not synchronized. Its iterators are fail-fast
390
What tuning parameter does IdentityHashMap have for performance?
expectedMaxSize - sets the expected maximum number of key-value mappings to optimize initial bucket count and reduce rehashing
391
MEMORY BOOSTER: IdentityHashMap
IdentityHashMap = Map + reference equality (==) instead of value equality (equals()). Use when you need to distinguish objects by identity not value. Common in serialization and proxy object tracking
392
What is a WeakHashMap in Java?
WeakHashMap is a Map backed by a Hashtable where entries are automatically removed by the garbage collector when the key is no longer strongly referenced. It allows null keys and null values and is not synchronized
393
What makes WeakHashMap unique compared to HashMap?
Entries in WeakHashMap are automatically removed when the key object is no longer reachable in the program - making it useful for cache-like scenarios where you do not want to prevent garbage collection
394
Is WeakHashMap thread-safe?
No - WeakHashMap is not synchronized. Use Collections.synchronizedMap() to make it thread-safe
395
MEMORY BOOSTER: WeakHashMap
WeakHashMap = HashMap + weak references for keys + automatic GC cleanup. When no strong reference to a key exists - the entry is removed automatically. Perfect for memory-sensitive caches. Not thread-safe
396
How can you make a Collection read-only in Java?
Use Collections.unmodifiableMap() - Collections.unmodifiableList() - Collections.unmodifiableSet() or Collections.unmodifiableCollection() to wrap the collection in a read-only view
397
What exception is thrown when you try to modify a read-only collection?
UnsupportedOperationException - thrown when a mutating operation like add() or remove() is called on an unmodifiable collection
398
MEMORY BOOSTER: Read-only Collections
Collections.unmodifiable___() = read-only wrapper. Any attempt to modify throws UnsupportedOperationException. Pattern: Collections.unmodifiableList/Set/Map/Collection(). Also Collections.emptyList/Set/Map() for immutable empty collections
399
When is UnsupportedOperationException thrown in Java Collections?
When an optional mutating operation like add() or remove() is called on a read-only or unmodifiable collection. It is an unchecked exception
400
MEMORY BOOSTER: UnsupportedOperationException
Unmodifiable collection + mutation attempt = UnsupportedOperationException. It is unchecked (extends RuntimeException). Common trigger: calling add() on Collections.unmodifiableList() or Arrays.asList() result
401
How can you sort Customer objects in an ArrayList by the firstName attribute?
Option 1: Implement Comparable in Customer class and override compareTo() to compare by firstName. Option 2: Create a Comparator that compares by firstName and pass it to Collections.sort(list - comparator)
402
MEMORY BOOSTER: Sorting custom objects
Comparable = built into the class = one sort order = compareTo(). Comparator = external = multiple sort orders = compare(o1 - o2). Collections.sort() works with both. Comparable for natural order. Comparator for custom or multiple orderings
403
What is the difference between a Synchronized Collection and a Concurrent Collection?
Synchronized Collections (via Collections.synchronizedXxx()) lock the entire collection for every operation. Concurrent Collections like ConcurrentHashMap lock only a portion of the collection giving much better performance under concurrency
404
Why do Concurrent Collections have better performance than Synchronized Collections?
Concurrent Collections use fine-grained locking or lock-free algorithms - locking only a segment or using CAS operations. Synchronized Collections lock the entire structure for every read and write
405
MEMORY BOOSTER: Synchronized vs Concurrent Collections
Synchronized = Collections.synchronizedXxx() = full lock = one thread at a time = simple but slow. Concurrent = ConcurrentHashMap / CopyOnWriteArrayList = partial lock = many threads simultaneously = complex but fast
406
In which scenario is ConcurrentHashMap most suited?
ConcurrentHashMap is best when there are multiple reader threads and one writer thread. The map is only locked during writes so reads are highly concurrent
407
How does ConcurrentHashMap perform when reads and writes are equal?
When there are equal numbers of readers and writers ConcurrentHashMap performs similarly to Hashtable or a synchronized HashMap - the benefit of partial locking is less pronounced
408
MEMORY BOOSTER: ConcurrentHashMap best scenario
ConcurrentHashMap shines with many readers + few writers. Reads are non-blocking. Writes lock only one segment. Equal readers and writers = similar to Hashtable. Many readers + one writer = huge performance win
409
What are the ways to create an empty Map in Java?
Option 1: Immutable empty map using Collections.emptyMap(). Option 2: Mutable empty map using new HashMap()
410
What is the difference between Collections.emptyMap() and new HashMap()?
Collections.emptyMap() returns an immutable singleton empty map - no entries can be added. new HashMap() creates a mutable empty map that can store entries
411
MEMORY BOOSTER: Empty Map creation
Collections.emptyMap() = immutable + singleton + reused instance. new HashMap() = mutable + new object. Choose emptyMap() for read-only placeholders. Choose new HashMap() when you need to add entries
412
What is the difference between remove() in Collection and remove() in Iterator?
Collection.remove() and List.remove() remove elements when no thread is iterating. Iterator.remove() safely removes the current element during iteration. Using Collection.remove() during iteration causes ConcurrentModificationException
413
When must you use Iterator.remove() instead of Collection.remove()?
Whenever you need to remove elements while iterating over a Collection with an Iterator. Using Collection.remove() during Iterator traversal throws ConcurrentModificationException
414
MEMORY BOOSTER: remove() Collection vs Iterator
Collection.remove() = use when NOT iterating. Iterator.remove() = use DURING iteration. Using Collection.remove() inside an Iterator loop = ConcurrentModificationException. Rule: if iterating - always remove through the Iterator
415
Between an Array and ArrayList which is preferred for storing objects?
ArrayList is generally preferred because it is dynamic - supports Generics for type safety - provides Iterator support and catches type errors at compile time. Use Array only when the size is fixed and known in advance
416
MEMORY BOOSTER: Array vs ArrayList for objects
ArrayList wins for objects: dynamic sizing + Generics + Iterator + compile-time type safety. Array wins only when: size is fixed + known in advance + performance is critical. Default choice for objects: ArrayList
417
Is it possible to replace Hashtable with ConcurrentHashMap in Java?
Yes but with care. Hashtable locks the whole map so compound operations like get-then-put are atomic. ConcurrentHashMap does not support this - you must use putIfAbsent() instead
418
What compound operation in Hashtable does not work the same in ConcurrentHashMap?
if(map.get(key) == null) map.put(key - value) is atomic in Hashtable but not in ConcurrentHashMap. Use map.putIfAbsent(key - value) in ConcurrentHashMap instead
419
MEMORY BOOSTER: Replacing Hashtable with ConcurrentHashMap
ConcurrentHashMap can replace Hashtable but watch for compound operations. Hashtable.get+put is atomic. ConcurrentHashMap is not - use putIfAbsent() instead. Also: ConcurrentHashMap allows no nulls while Hashtable does not allow nulls either
420
How is CopyOnWriteArrayList different from ArrayList and Vector?
CopyOnWriteArrayList is thread-safe without locking on reads - it copies the array on every write. ArrayList is not thread-safe. Vector is thread-safe but uses full synchronization causing contention. CopyOnWriteArrayList never throws ConcurrentModificationException
421
How does CopyOnWriteArrayList achieve thread-safety?
On every write operation (add - set - remove) it creates a fresh copy of the underlying array. Readers always see a consistent snapshot. No locks are needed for reading
422
MEMORY BOOSTER: CopyOnWriteArrayList vs ArrayList vs Vector
ArrayList = not thread-safe + fast. Vector = thread-safe + slow (full lock). CopyOnWriteArrayList = thread-safe + fast reads + slow writes (copies array on every write). Best for: read-heavy concurrent lists
423
Why does ListIterator have an add() method but Iterator does not?
ListIterator maintains pointers to both previous and next elements allowing safe insertion at the current position. Iterator only moves forward with a single pointer so there is no well-defined position to insert at
424
What happens after you call add() on a ListIterator?
The new element is inserted immediately before the element that would be returned by next(). A subsequent call to next() is unaffected. A call to previous() returns the newly added element
425
MEMORY BOOSTER: Why ListIterator has add()
Iterator = one direction = one pointer = no defined insertion point = no add(). ListIterator = two directions = two pointers (prev + next) = defined insertion point = add() makes sense. More navigation = more methods
426
Why do we sometimes get ConcurrentModificationException during iteration?
Because the Collection was structurally modified (element added or removed) while an Iterator was traversing it. The Iterator detects the structural change via a modification counter and throws the exception
427
MEMORY BOOSTER: ConcurrentModificationException
Cause: modifying a Collection while iterating it with a fail-fast Iterator. Fix: use Iterator.remove() during iteration - or use a ConcurrentCollection - or collect elements to remove in a separate list and remove after iteration
428
How will you convert a Map to a List in Java?
A Map has three views that can each become a List: new ArrayList(map.keySet()) for keys - new ArrayList(map.values()) for values - new ArrayList(map.entrySet()) for key-value pairs
429
MEMORY BOOSTER: Map to List conversion
Map has three views: keySet() - values() - entrySet(). Wrap any of them in new ArrayList() to get a List. Remember: entrySet() gives you Map.Entry objects containing both key and value
430
How can we create a Map with reverse view and lookup in Java?
JDK does not provide a built-in bidirectional map. Use BidiMap from Apache Commons Collections or BiMap from Google Guava. Both enforce one-to-one mapping between keys and values allowing lookup by value as well as by key
431
What is a bidirectional map?
A map where both keys and values are unique allowing lookup in both directions - finding a value by key and finding a key by value
432
MEMORY BOOSTER: Reverse lookup Map
JDK has no built-in bidirectional map. Use Apache Commons BidiMap or Guava BiMap. Both enforce 1-to-1 key-value mapping. Think of it as a two-way dictionary
433
How will you create a shallow copy of a Map in Java?
Option 1: Use the copy constructor of the Map implementation - new HashMap(sourceMap). Option 2: Use clone() method (not recommended). Wrap with Collections.synchronizedMap() if thread safety is needed during copy
434
Why should you use Collections.synchronizedMap() when copying a Map?
The copy constructor is not synchronized so another thread could modify the source map during copying. Wrapping with synchronizedMap() prevents this
435
MEMORY BOOSTER: Shallow copy of Map
new HashMap(sourceMap) = easiest shallow copy. clone() = works but not recommended. Neither is thread-safe during copying. Use Collections.synchronizedMap(sourceMap) first if other threads may modify during copy
436
Why can we not create a generic array in Java?
Arrays need to know the element type at runtime for type checking. Generics use type erasure - the type information is removed at runtime. This incompatibility means Java cannot create arrays with generic element types
437
What is type erasure in Java?
Type erasure is the process by which the Java compiler removes generic type information at runtime. The generic type parameter is replaced with Object or the type bound making type information unavailable at runtime
438
What exception would a generic array throw at runtime?
Without generics arrays throw ArrayStoreException if you insert the wrong type. With generics the type is erased at runtime so this check cannot be performed making generic arrays unsafe and therefore not allowed
439
MEMORY BOOSTER: No generic arrays in Java
Array = needs type info at runtime. Generics = type info erased at runtime. Conflict = no generic arrays allowed. Workaround: use ArrayList instead of T[]. If you must have an array use cast with @SuppressWarnings
440
What is a PriorityQueue in Java?
PriorityQueue is an unbounded queue based on a priority heap. Elements are retrieved in natural order or using a Comparator. It is not FIFO - the highest priority element is always retrieved first. It is not thread-safe and does not allow null values
441
Is PriorityQueue ordered in FIFO order?
No - PriorityQueue retrieves elements based on priority (natural ordering or Comparator) not insertion order
442
What is the time complexity of enqueue and dequeue in PriorityQueue?
O(log n) for both enqueing (offer/add) and dequeing (poll/remove) operations
443
Does PriorityQueue allow null values?
No - PriorityQueue does not allow null elements and does not allow objects without natural ordering unless a Comparator is provided
444
MEMORY BOOSTER: PriorityQueue
PriorityQueue = Queue + priority ordering + heap-based + not FIFO + not thread-safe + no nulls. O(log n) for add and remove. Smallest element first by default. Think of it as a self-sorting queue
445
What are the important points to remember while using Java Collections Framework?
Use generic interfaces not concrete types. Use Generics for type safety. Use Collections utility class for algorithms. Choose the right collection type for your need. Set initial capacity to avoid rehashing. Use immutable classes as Map keys
446
Why should you use immutable classes as keys in a Map?
Immutable keys cannot change their hashCode or equals behavior after being inserted. If a mutable key changes its hash after insertion the entry becomes unreachable in the Map
447
MEMORY BOOSTER: Java Collections best practices
6 rules: 1) Code to interfaces not implementations 2) Always use Generics 3) Use Collections utility methods 4) Pick the right collection type 5) Set initial capacity when known 6) Use immutable objects as Map keys
448
How can we pass a Collection to a method and ensure the method cannot modify it?
Wrap the Collection with Collections.unmodifiableCollection(c) before passing it. Any attempt by the method to call add() - remove() or clear() will throw UnsupportedOperationException
449
MEMORY BOOSTER: Pass Collection as read-only
Collections.unmodifiableCollection(c) = read-only wrapper. Pass the wrapped version to the method. Mutation attempt = UnsupportedOperationException. Works for List - Set - Map and Collection variants
450
How does a HashMap work internally in Java?
HashMap uses hashing. put() calls hashCode() on the key to find a bucket then stores the entry (key + value) as a Map.Entry object. get() calls hashCode() to find the bucket then uses equals() to find the exact key within the bucket
451
What is stored inside a HashMap bucket?
A Map.Entry object that holds both the key object and the value object
452
What happens when two keys hash to the same bucket in a HashMap?
Both entries are stored in the same bucket as a chain (linked list or tree in Java 8+). equals() is used to distinguish between them during lookup
453
MEMORY BOOSTER: How HashMap works
put(): hashCode() => find bucket => store Entry. get(): hashCode() => find bucket => equals() => return value. Bucket = storage slot. Entry = key+value pair. Hash collision = multiple entries in same bucket = use equals() to distinguish
454
How is HashSet implemented internally in Java?
HashSet internally uses a HashMap. When you create a HashSet a corresponding HashMap is created. When you add an element to the HashSet it is inserted as a key into the underlying HashMap with a constant dummy value
455
What is the dummy value used in HashSet's internal HashMap?
A constant static Object called PRESENT is used as the dummy value for all keys in the underlying HashMap
456
MEMORY BOOSTER: HashSet internals
HashSet = wrapper around HashMap. Element added to HashSet = key in internal HashMap. Dummy value = PRESENT constant. Uniqueness is guaranteed by HashMap's key uniqueness. No extra data structure needed
457
What is a NavigableMap in Java?
NavigableMap extends SortedMap and provides methods to navigate keys in both directions. Key methods include descendingKeySet() - descendingMap() - headMap() - tailMap() - lowerEntry() - floorEntry() - ceilingEntry() and higherEntry()
458
What is the difference between descendingKeySet() and descendingMap() in NavigableMap?
descendingKeySet() returns a NavigableSet of keys in reverse order. descendingMap() returns a full NavigableMap in reverse order with both keys and values. Both views reflect changes to the original map
459
What is the advantage of NavigableMap over Map?
NavigableMap combines the features of Map + SortedMap + navigation. It can return closest matches for a given key using lowerEntry - floorEntry - ceilingEntry and higherEntry methods
460
What do headMap() - tailMap() and subMap() return in NavigableMap?
headMap() returns entries less than a given key. tailMap() returns entries greater than a given key. subMap() returns entries between two given keys. All return views of the original map
461
MEMORY BOOSTER: NavigableMap
NavigableMap = SortedMap + navigation methods. lower/floor = below key. ceiling/higher = above key. head = before key. tail = after key. sub = between keys. TreeMap is the main implementation. Think of it as a sorted map with GPS
462
How will you sort objects by natural order in a Java List?
Use Collections.sort(list) which requires elements to implement Comparable and its compareTo() method. Alternatively pass a Comparator to Collections.sort(list - comparator) to define a custom sort order
463
MEMORY BOOSTER: Sort List by natural order
Collections.sort(list) = natural order = requires Comparable. Collections.sort(list - comparator) = custom order = requires Comparator. Both run in O(n log n). Comparable is in the class. Comparator is outside the class
464
How can we get a Stream from a List in Java?
From Java 8 onwards use the stream() method: myList.stream() returns a Stream of the list elements
465
Can we get a Map from a Stream in Java?
Yes - use the map() method on a Stream to transform each element. For example items.stream().map(item -> item.toLowerCase()) maps each item to its lowercase version. Use collect(Collectors.toMap()) to collect stream into a Map
466
MEMORY BOOSTER: Stream from List
myList.stream() = Stream from List (Java 8+). stream.map() = transforms each element. stream.collect(Collectors.toList()) = back to List. stream.collect(Collectors.toMap()) = to Map. Stream is lazy - nothing executes until a terminal operation is called
467
What are the popular implementations of Deque in Java?
ArrayDeque: resizable array implementation - not thread-safe - fail-fast iterator - faster than Stack and LinkedList for most operations. LinkedList: doubly linked list implementation - not synchronized - also implements List interface
468
What is ArrayDeque in Java?
ArrayDeque is a resizable array implementation of Deque. It is not thread-safe and its iterator is fail-fast. It is generally faster than Stack for stack operations and faster than LinkedList for queue operations
469
MEMORY BOOSTER: Deque implementations
Two main Deque implementations: ArrayDeque (array-backed + fast + not thread-safe) and LinkedList (node-based + also a List + not thread-safe). ArrayDeque is preferred for pure stack or queue use. LinkedList if you also need List operations