diff --git a/w8/AI_help.txt b/w8/AI_help.txt new file mode 100644 index 0000000..a95cc99 --- /dev/null +++ b/w8/AI_help.txt @@ -0,0 +1,32 @@ +Java泛型是“伪泛型”(类型擦除) + +运行时大部分泛型信息被擦掉,但: + +类的泛型信息(声明时)还能拿到 + +泛型基于“类型擦除” + +泛型在编译后变成:Object +但: + +int 不是对象 +Object 不能接收 int + +所以不能支持 int + +JVM设计限制 + +Java泛型是在编译器层实现的(不是JVM层) +→ JVM根本不知道泛型 + +解决方案:包装类 + +用: + +Integer 替代 int +Double 替代 double + +自动装箱: + +Cache cache = new Cache<>(); +cache.put("a", 1); // 自动装箱 \ No newline at end of file diff --git a/w8/Cache.java b/w8/Cache.java new file mode 100644 index 0000000..5d247cb --- /dev/null +++ b/w8/Cache.java @@ -0,0 +1,26 @@ +import java.util.HashMap; +import java.util.Map; + +public class Cache { + private Map 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(); + } +} \ No newline at end of file diff --git a/w8/Pair.java b/w8/Pair.java new file mode 100644 index 0000000..7dfbcbf --- /dev/null +++ b/w8/Pair.java @@ -0,0 +1,20 @@ +public class Pair { + 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 swap() { + return new Pair<>(value, key); + } +} \ No newline at end of file