3 changed files with 78 additions and 0 deletions
@ -0,0 +1,32 @@ |
|||
Java泛型是“伪泛型”(类型擦除) |
|||
|
|||
运行时大部分泛型信息被擦掉,但: |
|||
|
|||
类的泛型信息(声明时)还能拿到 |
|||
|
|||
泛型基于“类型擦除” |
|||
|
|||
泛型在编译后变成:Object |
|||
但: |
|||
|
|||
int 不是对象 |
|||
Object 不能接收 int |
|||
|
|||
所以不能支持 int |
|||
|
|||
JVM设计限制 |
|||
|
|||
Java泛型是在编译器层实现的(不是JVM层) |
|||
→ JVM根本不知道泛型 |
|||
|
|||
解决方案:包装类 |
|||
|
|||
用: |
|||
|
|||
Integer 替代 int |
|||
Double 替代 double |
|||
|
|||
自动装箱: |
|||
|
|||
Cache<String, Integer> cache = new Cache<>(); |
|||
cache.put("a", 1); // 自动装箱 |
|||
@ -0,0 +1,26 @@ |
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
|
|||
public class Cache<K, V> { |
|||
private Map<K, V> cache = new HashMap<>(); |
|||
|
|||
public void put(K key, V value) { |
|||
cache.put(key, value); |
|||
} |
|||
|
|||
public V get(K key) { |
|||
return cache.get(key); |
|||
} |
|||
|
|||
public boolean contains(K key) { |
|||
return cache.containsKey(key); |
|||
} |
|||
|
|||
public void remove(K key) { |
|||
cache.remove(key); |
|||
} |
|||
|
|||
public void clear() { |
|||
cache.clear(); |
|||
} |
|||
} |
|||
@ -0,0 +1,20 @@ |
|||
public class Pair<K, V> { |
|||
private K key; |
|||
private V value; |
|||
|
|||
public Pair(K key, V value) { |
|||
this.key = key; |
|||
this.value = value; |
|||
} |
|||
|
|||
public K getKey() { return key; } |
|||
public V getValue() { return value; } |
|||
|
|||
public void setKey(K key) { this.key = key; } |
|||
public void setValue(V value) { this.value = value; } |
|||
|
|||
// swap方法
|
|||
public Pair<V, K> swap() { |
|||
return new Pair<>(value, key); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue