You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
591 B
32 lines
591 B
Java泛型是“伪泛型”(类型擦除)
|
|
|
|
运行时大部分泛型信息被擦掉,但:
|
|
|
|
类的泛型信息(声明时)还能拿到
|
|
|
|
泛型基于“类型擦除”
|
|
|
|
泛型在编译后变成:Object
|
|
但:
|
|
|
|
int 不是对象
|
|
Object 不能接收 int
|
|
|
|
所以不能支持 int
|
|
|
|
JVM设计限制
|
|
|
|
Java泛型是在编译器层实现的(不是JVM层)
|
|
→ JVM根本不知道泛型
|
|
|
|
解决方案:包装类
|
|
|
|
用:
|
|
|
|
Integer 替代 int
|
|
Double 替代 double
|
|
|
|
自动装箱:
|
|
|
|
Cache<String, Integer> cache = new Cache<>();
|
|
cache.put("a", 1); // 自动装箱
|