← Java OOP Knowledge Map← Java OOP 知识地图
Generics & Collections

Generics & Collections

Generics let classes, interfaces, and methods receive type parameters. Collections are Java's common containers, and generics make them safer.泛型让 class、interface、method 可以接收“类型参数”。集合是 Java 里最常用的数据容器,泛型让集合更安全。

Why Generics

Why write List<String>?为什么写 List<String>

List<String> names = new ArrayList<>();
names.add("Alice");
String name = names.get(0);

List<String> tells the compiler that the list only stores strings, so many mistakes are caught at compile time.List<String> 告诉编译器:这个 list 里面只能放 String。这样很多错误在 compile time 就能发现。

Type Parameters

T/E/K/V are placeholdersT/E/K/V 是占位符

Letter字母Meaning常见意思Example例子
TTypeBox<T>
EElementList<E>
KKeyMap<K,V>
VValueMap<K,V>
Common Collections

Common collection intuition最常用的集合直觉

Collection集合Use when适合什么时候用
List<E>You need order and index.需要顺序和 index。
Set<E>You need uniqueness.需要去重。
Map<K,V>You need key-to-value lookup.需要通过 key 找 value。