3 changed files with 54 additions and 0 deletions
@ -0,0 +1,5 @@ |
|||||
|
3.AI协同学习:泛型擦除后如何通过反射获取泛型信息? |
||||
|
答案:擦除后,运行时拿不到类型参数k、V的实际值。但可以通过反射获取字段、方法参数/返回值上声明的泛型信息(如List<String>中的String) |
||||
|
4.思考题:为什么Java泛型不支持基本类型? |
||||
|
根本原因:Java泛型通过类型擦除实现,编译后所有泛型参数都被替换为Object(或上界类型)。而基本类型(int、double等)不继承自 object,无法直接放入0bject容器中。 |
||||
|
解法:使用对应的包装类(Integer Double).依赖自动装箱/拆箱 |
||||
@ -0,0 +1,26 @@ |
|||||
|
import java.util.HashMap; |
||||
|
import java.util.Map; |
||||
|
|
||||
|
public class Cache<K, V> { |
||||
|
private final 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 containsKey(K key) { |
||||
|
return cache.containsKey(key); |
||||
|
} |
||||
|
|
||||
|
public int size() { |
||||
|
return cache.size(); |
||||
|
} |
||||
|
|
||||
|
public void clear() { |
||||
|
cache.clear(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,23 @@ |
|||||
|
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; } |
||||
|
|
||||
|
// 交换后 key/value 类型可能变化,所以返回新的 Pair<V, K>
|
||||
|
public Pair<V, K> swap() { |
||||
|
return new Pair<>(this.value, this.key); |
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
Pair<String, Integer> p = new Pair<>("Age", 25); |
||||
|
Pair<Integer, String> swapped = p.swap(); |
||||
|
System.out.println(swapped.getKey() + "=" + swapped.getValue()); // 25=Age
|
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue