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 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 就能发现。
T/E/K/V are placeholdersT/E/K/V 是占位符
| Letter字母 | Meaning常见意思 | Example例子 |
|---|---|---|
| T | Type | Box<T> |
| E | Element | List<E> |
| K | Key | Map<K,V> |
| V | Value | Map<K,V> |
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。 |