Understanding Java Generics and Collections
Understanding Java Generics and Collections
methods.
Collection frameworks:
list & map
Generic T obj;
Test(T obj) {
{
T obj1; // An object of type T
U obj2; // An object of type U
class
[Link] = obj;
} Test(T obj1, U obj2)
public T getObject() { return {
[Link]; } this.obj1 = obj1;
} this.obj2 = obj2;
}
• A generic class is like a class Dpoint {
public static void main(String[] public void print()
regular class but uses type args) {
parameters (like <T>). { [Link](obj1);
• It can accept one or more // instance of Integer type [Link](obj2);
Test<Integer> iObj = new }
types, making the class Test<Integer>(15); }
reusable for different data
types. Such classes are [Link]([Link]()); class Dpoint
called parameterized classes. {
// instance of String type public static void main (String[]
Test<String> sObj args)
= new {
Test<String>("GeeksForGeeks"); Test <String, Integer> obj =
new Test<String,
[Link]([Link]()); Integer>("GfG", 15);
}
} - By polisetty Sai Teja [Link](); 4
}
• A generic method is a method that can work with different
data types using a type parameter. It lets you write one
method that works for all types, instead of repeating the
same logic.
• class Geeks {
Inheritance direction
downward
Super ? super T means: “some
unknown type that is T
or a supertype of T.”
? extends T ? super T
Feature
(Producer) (Consumer)
Some subtype of Some supertype
Meaning
T of T
Safe For Reading (get) Writing (add)
Reading Returns T Returns Object
❌ Not allowed ✅ Can add T
Writing
(except null) values
List<? extends List<? super
Example
Number> Integer>
Basket
Basket producing
Analogy consuming
Apples
Apples
→ ? super T
• If you need to both read Sort with a
comparator
Comparator<?
super T>
A comparator of a
supertype can
and write as the same T → compare Ts.
— “one
return new Page<>(items, 1, 10);
}
Quiz 19
- By polisetty Sai Teja
20
Type parameters cannot be
referenced from a ____ context.
To accept any subtype of
A) static B) dynamic C)
generic D) override
15
A) extends B) super C) over
Question Answer
1 Generics provide type _____. safety (A)
Answer
19 Type parameters cannot be A) static
referenced from a ____ context.
- By polisetty Sai Teja 16
20 To accept any subtype of A) extends
List
• an ordered collection that allows
duplicates. - Order matters (index
based).
• “Think Spotify playlist—order
matters, the same song can repeat.”
• Example:
List<String> names = new
ArrayList<>();
[Link]("A"); [Link]("B");
[Link]("A"); // duplicates allowed
[Link]([Link](1)); //
"B"
Spotify —
Playlist editor class Playlist {
private final List<Track> tracks = ??? ;
(ordering,
duplicates, void add(Track t) { ??? }
allowed
// duplicates
ArrayList general purpose; lots of get O(1), add-end contiguous array; ensureCapacity
reads; append-heavy O(1), insert/remove helps; great default
middle O(n)
LinkedList mostly head/tail ops; lots of get O(n), higher memory; random access
listIterator inserts/removes add/remove ends slow; usually prefer ArrayList or
O(1) ArrayDeque for queues/stacks
CopyOnWriteArrayList many reads, very few get O(1), write O(n) snapshot iterators; great for
writes, iteration must never (copies array) listeners/observers
fail
[Link](.. need a synchronized must synchronized(list) { iterate }
.) wrapper to iterate safely
Unmodifiable ([Link], you want read-only views or of/copyOf throw on mutate &
[Link], copies disallow nulls
[Link])
Quick rules:
•Default: ArrayList.
Implementation •For queue/stack: use ArrayDeque, not LinkedList.
•For read-mostly shared lists: CopyOnWriteArrayList.
- By polisetty Sai Teja 19
Core • List<String> l = new ArrayList<>();
Api's • [Link]("red");
• [Link](0, "blue");
// append
// insert at index
• [Link](1, "green"); // replace
• [Link]("blue"); // remove by value (first
match)
• [Link](0); // remove by index
• boolean ok = [Link]("red");
• int i = [Link]("red"); // first index, -1 if not
found
• List<String> view = [Link](0, 1); // [0..1)
• [Link]([Link]()); // or
[Link](null) for natural
• [Link](String::toUpperCase);
• [Link](s -> [Link]() < 4);
• String[] arr = [Link](new String[0]); // or
[Link](String[]::new) (Java 11+)
- By polisetty Sai Teja 20
• var a = [Link]("x","y"); // •“[Link] is a
Immutabilit fixed-size, backed by array hotel room with nailed-
down furniture;
y & fixed- • // [Link]("z"); //
UnsupportedOperationException •[Link] is the museum
size traps: • [Link](0,"X"); // allowed (still fixed-
size)
—no touching.”
• var c =
[Link](new
ArrayList<>(a)); // read-only view of
a *copy*
- By polisetty Sai Teja 21
SubList is a view
• subList(from, to) returns a window into
the original list.
• Structural changes to parent or sublist
can cause
ConcurrentModificationException.
• If you need independence: new
ArrayList<>([Link](...))
var base = new ArrayList<>([Link](10,20,30,40,50));
var mid = [Link](1,4); // [20,30,40]
[Link](0, 200); // base now [10,200,30,40,50]
var copy = new ArrayList<>(mid);
ArrayList appends are ensureCapacity(n) before trimToSize() can free LinkedList: each node Need a queue/stack?
amortized O(1); middle big appends avoids memory after big has pointers → higher Prefer ArrayDeque
inserts/removes O(n) repeated grows. removals. memory, slow random (faster, no capacity
(shift). access; shines only for boxing).
frequent head/tail ops
with iterator already
positioned.
Answers
access is _____.
20 [Link]() (Java 16+) A) unmodifiable
- By polisetty Sai Teja returns a ____ list. 28
Map
• A Map<K,V> stores key → value pairs with
unique keys.
• Lookup by key (not by index).
• Typical ops: put, get, containsKey, remove,
size, isEmpty.
• Views: keySet(), values(), entrySet()
Map<String, String> phone = new HashMap<>();
[Link]("Alice", "999-111");
[Link]("Bob", "999-222");
[Link]([Link]("Alice")); // 999-
111
[Link]([Link]("Eve"));//
false
// Iteration patterns
for ([Link]<Integer,String> e : [Link]()) {
[Link]([Link]() + " → " + [Link]());
}
[Link]((k,v) -> [Link](k + ":" + v));
Ordering }
tricks:
• TreeMap (sorted + range queries):
TreeMap<Integer,String> tm = new TreeMap<>();
[Link](10,"A"); [Link](20,"B"); [Link](30,"C");
[Link](21); // 20
[Link](19).getValue(); // "B"
[Link](10, true, 20, false); // [10..20)
Don’t mutate a key after put! If fields used in equals/hashCode change, the entry becomes “lost” in
the wrong bucket.
Type Rule
HashMap/ allow one null key + many null values.
LinkedHashMap
TreeMap no null key with natural ordering (NPE).
ConcurrentHashMap no null keys or values (to avoid ambiguity
with “missing”).
// or explicit iterator
for (Iterator<[Link]<K,V>> it =
[Link]().iterator(); [Link]();) {
var e = [Link]();
if (shouldRemove(e)) [Link]();
}
Spotify — user → playlists Each user has many playlists; each playlist
(computeIfAbsent) has tracks.
Instagram/Twitter — trending
hashtags (ConcurrentHashMap + Many threads updating counts safely.
merge)
- By polisetty Sai Teja 39
Question Options
1 General-purpose Map with O(1) A) HashMap B) TreeMap C)
lookups? LinkedHashMap D) EnumMap
2 Map preserving insertion order? A) TreeMap B) LinkedHashMap C)
HashMap D) WeakHashMap
3 Map with keys kept sorted? A) TreeMap B) HashMap C)
LinkedHashMap D) IdentityHashMap
4 High-throughput thread-safe A) Hashtable B) ConcurrentHashMap
Map? C) WeakHashMap D) EnumMap
Question Options
5 Map specialized for enum keys? A) TreeMap B) EnumMap C) HashMap
D) IdentityHashMap 11 Return fallback when key A) getOrDefault B) orElse C)
missing: _____. optional D) defaultGet
6 Map comparing keys by A) IdentityHashMap B) HashMap C)
reference identity? TreeMap D) EnumMap 12 Remove only if key maps to A) remove B) delete C) clear
given value: _____. D) prune
7 Map that drops entries when A) WeakHashMap B)
keys are GC’d? ConcurrentHashMap C) LinkedHashMap 13 Unmodifiable factory with A) [Link] B) [Link] C)
D) TreeMap literals: _____. [Link] D)
[Link]
8 With new A) insertion B) access C) hash D)
LinkedHashMap(16,0.75f, true), random 14 Unmodifiable defensive copy of A) [Link] B) [Link] C)
ordering is _____. another Map: _____. unmodifiableMap D) clone
9 Create value container if A) merge B) computeIfAbsent C) 15 Nearest key ≤ k: _____. A) lowerKey B) ceilingKey C)
missing: _____. putIfAbsent D) getOrDefault floorKey D) higherKey
10 Combine counts (old + 1): _____. A) replace B) merge C) compute D) 16 Nearest entry ≥ k: _____. A) ceilingEntry B) floorEntry
put C) higherEntry D) lowerEntry
17 Range view between two keys: A) headMap B) tailMap C)
_____. subMap D) sliceMap
18 View for iterating key+value A) keySet B) values C)
pairs: _____. entrySet D) pairSet
Quiz 19