diff --git a/w8/AI协同学习 b/w8/AI协同学习 new file mode 100644 index 0000000..2d76a59 --- /dev/null +++ b/w8/AI协同学习 @@ -0,0 +1,23 @@ +① 问题:Java 泛型擦除后如何通过反射获取泛型信息? +核心原理:Java 泛型在编译时会进行「类型擦除」,大部分泛型信息会被擦除为Object。但在以下场景中,编译器会保留部分泛型信息,可通过反射获取: +1. 继承 / 实现泛型父类 / 接口 +当一个类继承了带泛型的父类(或实现带泛型的接口),编译器会在class文件中保留父类的泛型参数。 +2.获取字段 / 方法的泛型信息 +可以通过Field.getGenericType()和Method.getGenericParameterTypes()获取字段、方法声明时的泛型信息。 + +② 用 AI 审查Cache 代码 +审查结果:你的Cache实现结构清晰,封装性良好,完全符合泛型类的设计规范。 +• 底层采用HashMap存储键值对,实现了put/get/remove/clear等核心缓存操作,功能完整。 +• 泛型参数K和V使用正确,实现了类型安全,编译时即可检查类型错误。 +• 建议:可以添加缓存过期策略、线程安全控制(如ConcurrentHashMap)或 LRU 淘汰策略,进一步提升健壮性。 + +思考题:为什么 Java 泛型不支持基本类型? +核心原因是Java 的「类型擦除」机制,具体分三点说明: +1. 类型擦除后会变成 Object +Java 泛型在编译后会被擦除为Object类型,而基本类型(如int、char)不是对象,无法直接向上转型为Object。 +比如List会被擦除为List,但int无法被擦除为Object,因此语法不支持。 +2. 基本类型没有继承关系 +泛型的本质是「引用类型占位符」,而基本类型是独立的,不继承任何对象类型,无法参与泛型的多态机制。 +3. Java 提供了包装类替代方案 +虽然不能直接用基本类型,但可以使用它们的包装类(如Integer、Character),配合自动装箱 / 拆箱机制,实现和基本类型几乎一样的使用体验。 +比如List会被擦除为List,而Integer是对象,可以正常参与类型擦除。 diff --git a/w8/Cache.java b/w8/Cache.java new file mode 100644 index 0000000..59660b9 --- /dev/null +++ b/w8/Cache.java @@ -0,0 +1,32 @@ +import java.util.HashMap; +import java.util.Map; + +public class Cache { + private final 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 void remove(K key) { + cache.remove(key); + } + + public void clear() { + cache.clear(); + } + + public int size() { + return cache.size(); + } + + public void printAll() { + for (Map.Entry entry : cache.entrySet()) { + System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); + } + } +} \ No newline at end of file diff --git a/w8/Pair.java b/w8/Pair.java new file mode 100644 index 0000000..8889aac --- /dev/null +++ b/w8/Pair.java @@ -0,0 +1,27 @@ +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; + } + + // 交换 key 和 value + public static Pair swap(Pair pair) { + return new Pair<>(pair.getValue(), pair.getKey()); + } + + @Override + public String toString() { + return "Pair{key=" + key + ", value=" + value + "}"; + } +} \ No newline at end of file diff --git a/w8/TestMain.java b/w8/TestMain.java new file mode 100644 index 0000000..0a6ba73 --- /dev/null +++ b/w8/TestMain.java @@ -0,0 +1,20 @@ +public class TestMain { + public static void main(String[] args) { + // 测试 Pair + Pair pair = new Pair<>("年龄", 20); + System.out.println("原来:" + pair); + + Pair afterSwap = Pair.swap(pair); + System.out.println("交换后:" + afterSwap); + + // 测试 Cache + System.out.println("\n=== 测试缓存 ==="); + Cache cache = new Cache<>(); + + cache.put("语文", 90); + cache.put("数学", 95); + + System.out.println("获取语文:" + cache.get("语文")); + cache.printAll(); + } +} \ No newline at end of file