Browse Source

添加 w8 泛型练习(Pair 与 Cache)

main
wangjiashuo 3 weeks ago
parent
commit
b26992411a
  1. BIN
      w8/Cache.class
  2. 50
      w8/Cache.java
  3. BIN
      w8/Pair.class
  4. 46
      w8/Pair.java
  5. 15
      w8/思考题.txt

BIN
w8/Cache.class

Binary file not shown.

50
w8/Cache.java

@ -0,0 +1,50 @@
import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
private final Map<K, V> cache;
public Cache() {
this.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 void remove(K key) {
cache.remove(key);
}
public void clear() {
cache.clear();
}
public int size() {
return cache.size();
}
public static void main(String[] args) {
Cache<String, Integer> studentCache = new Cache<>();
studentCache.put("张三", 18);
studentCache.put("李四", 20);
System.out.println("张三的年龄:" + studentCache.get("张三"));
System.out.println("缓存是否包含王五:" + studentCache.containsKey("王五"));
studentCache.remove("李四");
System.out.println("移除李四后缓存大小:" + studentCache.size());
studentCache.clear();
System.out.println("清空后缓存大小:" + studentCache.size());
}
}

BIN
w8/Pair.class

Binary file not shown.

46
w8/Pair.java

@ -0,0 +1,46 @@
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 void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public void swap() {
Object temp = key;
key = (K) value;
value = (V) temp;
}
@Override
public String toString() {
return "Pair{" +
"key=" + key +
", value=" + value +
'}';
}
public static void main(String[] args) {
Pair<String, Integer> pair = new Pair<>("年龄", 20);
System.out.println("交换前:" + pair);
pair.swap();
System.out.println("交换后:" + pair);
}
}

15
w8/思考题.txt

@ -0,0 +1,15 @@
为什么Java泛型不支持基本类型?
核心原因是Java泛型的类型擦除机制,以及基本类型和引用类型的存储方式差异,具体分为以下几点:
1. 类型擦除导致的兼容问题
Java泛型在编译后会被擦除为  Object (或上界类型),而基本类型(如  int 、 double )不是  Object  的子类,无法直接赋值给  Object 。如果允许泛型使用基本类型,擦除后的代码会出现类型不匹配的问题。
2. 自动装箱/拆箱的本质
虽然我们可以用  List<Integer>  间接实现“存储int”的效果,但这并不是直接支持基本类型,而是利用了自动装箱(autoboxing)机制:编译器会自动将  int  转换为  Integer (包装类),本质上存储的还是引用类型。
3. 内存模型差异
基本类型存储在栈中,占用固定大小的内存(如  int  占4字节);而引用类型存储在堆中,栈中仅保存对象的引用。如果泛型直接支持基本类型,JVM需要为每个基本类型生成不同的类实现,会导致类爆炸,违背了泛型“一份代码,多种类型”的设计初衷。
4. 历史兼容考虑
Java泛型是在JDK 1.5引入的,为了兼容之前的非泛型代码(如  ArrayList ),采用了擦除实现。如果直接支持基本类型,会打破这种向后兼容性,导致旧代码无法运行。
Loading…
Cancel
Save