CH9 - Collections and Generics Flashcards

(50 cards)

1
Q

<> - Diamond operator

A

Diamond operator cannot be used as the type in a variable declaration

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

var with generics

A

var infers the type from the right side of the declaration, whereas the diamond operator infers it from the left side.

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

var map = new HashMap<>();

Is it valid declaration?

A

This compiles.

This is equivalent to the following:
HashMap<Object, Object> map = new HashMap<Object, Object>();

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

Ararys.AsList(varargs)

A

Returns fixed size list backed by an array.
Can only be elements replaced.

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

Overloaded remove() methods

A

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.

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

Set interface implementations

A

-HashSet
-LinkedHashSet
-TreeSet

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

equals() & hashCode()

A

equals() - is used to determine equality

hashCode() - is used to know which bucket to look in.

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

Bucket strategy for HashSet and HashMap

A

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

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

TreeMap null keys

A

❌ (TreeMap doesn’t allow null keys unless comparator handles it)

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

Map replace(K key, V value) method

A

Replaces value for given key if key is set. Returns original value or null if none.

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

Comparable

A

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

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

🤔 What happens if a class doesn’t implement Comparable?

A

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.

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

compareTo() vs equals()

A

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.

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

🧭 What is Comparator?

A

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

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

Comparable vs Comparator

A

✅ 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.).

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

🔗 What is Comparator Chaining?

A

Chaining lets you combine multiple comparisons into a single sort logic, using methods like:

-thenComparing()
-reversed()

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

Comparator Chaining Cheatsheet:

A

-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

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

binarySearch()

A

🧠 Summary
Fast search on sorted data

-Returns index if found
-Returns -(insertion_point) - 1 if not found
-Works with arrays and lists

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

Unbounded Wildcard <?>

A

✅Represents an unknown type.

✅Useful when you only need to read from a structure, not write to it.

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

Upper Bounded Wildcard <? extends T>

A

✅ 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.

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

Lower Bounded Wildcard <? super T>

A

✅ 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.

22
Q

PECS Rule (Producer Extends, Consumer Super)

A

✅ 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).

23
Q

List<?> list6 = new ArrayList<? extends A>();

Is it valid?

A

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.

24
Q

System.gc() + System.runFinalization()

A

Хотя явно вызывать сборку мусора в Java не рекомендуется, комбинация System.gc() и System.runFinalization() может быть полезна в тестах, профилировании и при ручном контроле над ресурсами во время разработки

25
B third(List list) { return new B(); // ❌ DOES NOT COMPILE } Why is it so?
"B is some type that extends A. I don't know what it is right now, but the compiler will figure it out when someone calls this method." The problem is: at runtime, the exact type of B is erased. The JVM doesn’t know what B is, so it can’t safely create a new instance of it. Java generics are compile-time only — the actual type parameter is not available at runtime, so the compiler refuses to allow this:
26
void fifth(List list) { } // ❌ DOES NOT COMPILE
Because X super B is not valid Java syntax in generic type declarations. Java doesn't allow bounded wildcards (super, extends) directly in the type parameter () like that. The super and extends keywords are meant to be used with wildcards (?), not with generic type parameters. ✅ What Java Allows: ✅ List → wildcard with lower bound ✅ List → wildcard with upper bound ✅ → bounded type parameter ❌ List → invalid syntax void fifth(List list) { // X is known and is some subtype of B }
27
Create Infinite Streams
- Stream.generate() - Stream.iterate(seed, unaryOperator) -unaryOperator -> a function to produce the next element from the previouse one Stream.iterate(seed, predicate, unaryOperator) * predicate - a condition that must be true for the next valie to be included in the stream
28
Reductions
Special type of terminal oepration where all of the contents of the stream are combined into a single primitive or Object.
29
public long count()
Determines number of elements in a finite stream. For infinite stream, it never terminates.
30
Optional min (Comparator c); Optional max (Comparator c);
Find the smallest or largest valie in finite stream according to that sort order. They return Optional rather than the value.
31
findAny() findFirst()
Return an element of the stream unless the stream is empty. If the stream is empty, they return an empty Optional
32
-allMatch() -anyMatch() -noneMatch()
Return boolean value, not reduction, sometimes terminates
33
forEach()
void return does not terminate, no reduction
34
reduce()
reduce() methods combine a stream into a single object. They are reductions which means they process all elements.
35
collect()
The Stream.collect() method in Java is a terminal operation that transforms the elements of a stream into a collection, string, or another mutable container like a map or summary result. Special type of reduction called mutable reduction.
36
filter()
It returns a Stream with elements that match a given expression.
37
distinct ()
returns a stream with duplicate values are removed. The duplicates do not need to be adjacent to be removed
38
limit() & skip()
limit(n) - keeps the first n elements skip(n) - skips the first n elements
39
map()
Creates one-to-one mapping from the elements in the stream to the elements of the next step in the stream.
40
flatMap()
It takes each element in the stream and makes any elements it contains top-level elements in a single stream.
41
sorted()
It returns a stream with elements sorted.
42
peek()
peek() is an intermediate operation. It lets you look at each element in the stream without modifying it. Typically used for debugging, logging, or side effects.
43
flatMap()
For each element in a stream, flatMap() produces a stream of values, and then flattens them all into one stream. 💡 Rule of Thumb Use flatMap() when each element might give you 0, 1, or many new elements, and you want them all in one flat stream.
44
Primitive Streams
✅ IntStream - used for primitive types - int, short, byte and char ✅ LongStream - primitive type long ✅ DoubleStream - primitive type double and float
45
✅ Optional Types for Primitives
Primitive | Optional Type ----------------------------------------- int | OptionalInt long | OptionalLong double | OptionalDouble
46
🔍 What is IntSummaryStatistics?
A class in java.util that collects statistics — like count, sum, min, max, and average — while processing an IntStream.
47
🔍 What Does "Streams Are Lazily Created" Mean?
➤ Stream operations don’t run immediately — they run only when needed. Specifically: -Intermediate operations (map, filter, flatMap, etc.) are lazy — they define what to do, but don’t do it yet. -Terminal operations (forEach, collect, findFirst, etc.) trigger actual execution.
48
🧠 Why Is Lazy Evaluation Useful for Streams?
✅ Efficiency: Stream stops early if it finds what it needs. ✅ Less memory usage: Items are processed one-by-one, not all loaded/stored. ✅ Supports infinite streams: You can write Stream.iterate(...) or generate(...) safely.
49
Collectors.toList() va toList()
Collectors.toList() => gives a mutable list toList() => gives immutabe list.
50