CH9 - Collections and Generics Flashcards
(50 cards)
<> - Diamond operator
Diamond operator cannot be used as the type in a variable declaration
var with generics
var infers the type from the right side of the declaration, whereas the diamond operator infers it from the left side.
var map = new HashMap<>();
Is it valid declaration?
This compiles.
This is equivalent to the following:
HashMap<Object, Object> map = new HashMap<Object, Object>();
Ararys.AsList(varargs)
Returns fixed size list backed by an array.
Can only be elements replaced.
Overloaded remove() methods
The one from Collection removes object that matches parameter. By contrast, the one from List removes an element at specified index.
Remember removing from Integer List with index and with value. int removes by index, Integer removes by value.
Set interface implementations
-HashSet
-LinkedHashSet
-TreeSet
equals() & hashCode()
equals() - is used to determine equality
hashCode() - is used to know which bucket to look in.
Bucket strategy for HashSet and HashMap
Java 21 uses LinkedList for buckets in HashMap and HashSet initially, but switches to red-black trees when necessary.
✅ Uses LinkedList for small buckets
✅ Automatically treeifies to TreeNode when a bucket gets large
❌ Does not exclusively use LinkedList or TreeMap — it adapts dynamically
TreeMap null keys
❌ (TreeMap doesn’t allow null keys unless comparator handles it)
Map replace(K key, V value) method
Replaces value for given key if key is set. Returns original value or null if none.
Comparable
The Comparable interface is a way to define the natural order for objects of a class.
Package: java.lang.Comparable
If you want to sort your objects (e.g., Collections.sort(list) or store them in sorted structures like TreeSet or TreeMap), Java needs to know how to compare them.
🧠 It’s used for default sorting
🧠 Only one compareTo() rule per class
🧠 If you want multiple sort options, use Comparator instead
🤔 What happens if a class doesn’t implement Comparable?
If you try to use your custom class in a data structure that needs to compare elements (like TreeSet, TreeMap, or Collections.sort()), and your class does not implement Comparable, Java will throw a runtime error or compile-time error, depending on the situation.
compareTo() vs equals()
If you write a class that implements Comparable, you introduce new business logic for determining equality.
If you override one, you usually want to override the other too, and make them consistent.
They’re related but not the same — and making them match helps avoid weird bugs.
🧭 What is Comparator?
Comparator is a functional interface used to define custom ways to compare two objects — outside the class itself.
📦 It’s in: java.util.Comparator
✅ When to use Comparator?
-When you want multiple ways to sort
-When you can’t or don’t want to change the class to implement Comparable
Comparable vs Comparator
✅ Use Comparable when you want a natural ordering (e.g., name alphabetically).
✅ Use Comparator when you want custom or multiple sort orders (e.g., sort by age, name, etc.).
🔗 What is Comparator Chaining?
Chaining lets you combine multiple comparisons into a single sort logic, using methods like:
-thenComparing()
-reversed()
Comparator Chaining Cheatsheet:
-comparing() Base comparator (e.g., by name)
-thenComparing() Adds tie-breaker comparison
-reversed() Reverses current chain
-comparingInt() Optimized for int fields
-comparingDouble() Optimized for double fields
binarySearch()
🧠 Summary
Fast search on sorted data
-Returns index if found
-Returns -(insertion_point) - 1 if not found
-Works with arrays and lists
Unbounded Wildcard <?>
✅Represents an unknown type.
✅Useful when you only need to read from a structure, not write to it.
Upper Bounded Wildcard <? extends T>
✅ Accepts T or any subtype of T.
✅ Good for reading (covariant) but not safe for writing.
Imagine:
-List<? extends Fruit> is a box of some specific type of fruit, but you don’t know if it’s apples or oranges.
-You’re allowed to take fruit out (read), but not put any in (write), because you might add the wrong kind.
Lower Bounded Wildcard <? super T>
✅ Accepts T or any supertype of T.
✅ Good for writing (contravariant), limited for reading.
Imagine:
-List<? super Apple> is a box that can hold apples or any of their supertypes.
-You can put apples in (write), but when you take one out, you only know it’s some kind of fruit or object — not necessarily an apple.
PECS Rule (Producer Extends, Consumer Super)
✅ Use extends when the generic type is producing data (e.g., reading from a collection).
✅ Use super when the generic type is consuming data (e.g., writing to a collection).
List<?> list6 = new ArrayList<? extends A>();
Is it valid?
No, Compilation Error.
In Java, you can’t use a wildcard like ? extends A in a constructor (new) — the compiler doesn’t know what concrete type to instantiate.
new ArrayList<? extends A>(); // ❌ Not allowed
Why? Because the constructor needs a real, concrete type, not a wildcard. ? extends A is a placeholder used in declarations, not instantiations.
System.gc() + System.runFinalization()
Хотя явно вызывать сборку мусора в Java не рекомендуется, комбинация System.gc() и System.runFinalization() может быть полезна в тестах, профилировании и при ручном контроле над ресурсами во время разработки