From d5950341dd8439c54e6e446cd3335aa8fcfc1c7e Mon Sep 17 00:00:00 2001 From: baihuijuan <3078948726@qq.com> Date: Thu, 7 May 2026 15:15:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90Pair=E5=8F=8A=E5=85=B6sw?= =?UTF-8?q?ap=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w8/AI | 5 +++++ w8/Cache.java | 26 ++++++++++++++++++++++++++ w8/Pair.java | 23 +++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 w8/AI create mode 100644 w8/Cache.java create mode 100644 w8/Pair.java diff --git a/w8/AI b/w8/AI new file mode 100644 index 0000000..8efb943 --- /dev/null +++ b/w8/AI @@ -0,0 +1,5 @@ +3.AI协同学习:泛型擦除后如何通过反射获取泛型信息? +答案:擦除后,运行时拿不到类型参数k、V的实际值。但可以通过反射获取字段、方法参数/返回值上声明的泛型信息(如List中的String) +4.思考题:为什么Java泛型不支持基本类型? +根本原因:Java泛型通过类型擦除实现,编译后所有泛型参数都被替换为Object(或上界类型)。而基本类型(int、double等)不继承自 object,无法直接放入0bject容器中。 +解法:使用对应的包装类(Integer Double).依赖自动装箱/拆箱 \ No newline at end of file diff --git a/w8/Cache.java b/w8/Cache.java new file mode 100644 index 0000000..01b861c --- /dev/null +++ b/w8/Cache.java @@ -0,0 +1,26 @@ +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 boolean containsKey(K key) { + return cache.containsKey(key); + } + + public int size() { + return cache.size(); + } + + 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..d572c9c --- /dev/null +++ b/w8/Pair.java @@ -0,0 +1,23 @@ +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 类型可能变化,所以返回新的 Pair + public Pair swap() { + return new Pair<>(this.value, this.key); + } + + public static void main(String[] args) { + Pair p = new Pair<>("Age", 25); + Pair swapped = p.swap(); + System.out.println(swapped.getKey() + "=" + swapped.getValue()); // 25=Age + } +} \ No newline at end of file