Quick Reference
| Topic | File |
|---|
| Nulls, Optional, autoboxing | INLINECODE0 |
| Collections and iteration traps |
collections.md |
| Generics and type erasure |
generics.md |
| Concurrency and synchronization |
concurrency.md |
| Classes, inheritance, memory |
classes.md |
| Streams and CompletableFuture |
streams.md |
| Testing (JUnit, Mockito) |
testing.md |
| JVM, GC, modules |
jvm.md |
Critical Rules
- -
== compares references, not content — always use .equals() for strings - Override
equals() must also override hashCode() — HashMap/HashSet break otherwise - INLINECODE12 throws if empty — use
orElse(), orElseGet(), or INLINECODE15 - Modifying while iterating throws
ConcurrentModificationException — use Iterator.remove() - Type erasure: generic type info gone at runtime — can't do
new T() or INLINECODE18 - INLINECODE19 ensures visibility, not atomicity —
count++ still needs synchronization - Unboxing null throws NPE —
Integer i = null; int x = i; crashes - INLINECODE22 uses reference for values outside -128 to 127 — use INLINECODE23
- Try-with-resources auto-closes — implement
AutoCloseable, Java 7+ - Inner classes hold reference to outer — use static nested class if not needed
- Streams are single-use — can't reuse after terminal operation
- INLINECODE25 vs
thenCompose — compose for chaining CompletableFutures - Records are implicitly final — can't extend, components are final
- INLINECODE27 mismatch breaks deserialization — always declare explicitly
快速参考
| 主题 | 文件 |
|---|
| 空值、Optional、自动装箱 | nulls.md |
| 集合与迭代陷阱 |
collections.md |
| 泛型与类型擦除 | generics.md |
| 并发与同步 | concurrency.md |
| 类、继承、内存 | classes.md |
| 流与CompletableFuture | streams.md |
| 测试(JUnit、Mockito) | testing.md |
| JVM、GC、模块 | jvm.md |
关键规则
- - == 比较的是引用而非内容——字符串始终使用 .equals()
- 重写 equals() 必须同时重写 hashCode()——否则HashMap/HashSet会出错
- 空值时调用 Optional.get() 会抛出异常——应使用 orElse()、orElseGet() 或 ifPresent()
- 迭代时修改会抛出 ConcurrentModificationException——应使用Iterator.remove()
- 类型擦除:泛型类型信息在运行时消失——不能使用 new T() 或 instanceof List
- volatile 保证可见性而非原子性——count++ 仍需同步
- 拆箱空值会抛出NPE——Integer i = null; int x = i; 会崩溃
- Integer == Integer 对-128到127范围外的值使用引用比较——应使用 .equals()
- try-with-resources自动关闭——需实现 AutoCloseable,Java 7+
- 内部类持有外部类的引用——如不需要应使用静态嵌套类
- 流只能使用一次——终端操作后无法重复使用
- thenApply 与 thenCompose——compose用于链式组合CompletableFuture
- 记录(Record)隐式为final——不可继承,组件为final
- serialVersionUID 不匹配会破坏反序列化——始终显式声明