故春 2 months ago
parent
commit
ba5c742f64
  1. 48
      W8/Cache.java
  2. 48
      W8/Pair.java
  3. 30
      W8/TestGeneric.java

48
W8/Cache.java

@ -0,0 +1,48 @@
import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
private final Map<K, V> cache;
public Cache() {
cache = new HashMap<>();
}
// 存入缓存
public void put(K key, V value) {
cache.put(key, value);
}
// 读取缓存
public V get(K key) {
return cache.get(key);
}
// 移除缓存
public V remove(K key) {
return cache.remove(key);
}
// 清空缓存
public void clear() {
cache.clear();
}
// 获取缓存大小
public int size() {
return cache.size();
}
// 测试
public static void main(String[] args) {
Cache<String, Integer> ageCache = new Cache<>();
ageCache.put("张三", 20);
ageCache.put("李四", 22);
System.out.println("张三的年龄:" + ageCache.get("张三"));
System.out.println("缓存大小:" + ageCache.size());
ageCache.remove("李四");
System.out.println("移除李四后缓存大小:" + ageCache.size());
}
}

48
W8/Pair.java

@ -0,0 +1,48 @@
public class Pair<K, V> {
private K key;
private V value;
// 构造方法
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
// 交换方法:交换 key 和 value 的值
public Pair<V, K> swap() {
return new Pair<>(value, key);
}
// Getter/Setter
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;
}
@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<Integer, String> swapped = pair.swap();
System.out.println("交换后:" + swapped);
}
}

30
W8/TestGeneric.java

@ -0,0 +1,30 @@
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
public class GenericReflectDemo {
// 成员变量带泛型
private List<String> list;
public static void main(String[] args) throws NoSuchFieldException {
// 1. 获取成员变量的泛型类型
Field field = GenericReflectDemo.class.getDeclaredField("list");
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) genericType;
Type[] actualTypeArgs = pType.getActualTypeArguments();
for (Type arg : actualTypeArgs) {
System.out.println("泛型参数类型:" + arg); // 输出 class java.lang.String
}
}
// 2. 获取父类的泛型参数
class MyList extends ArrayList<String> {}
Type superType = MyList.class.getGenericSuperclass();
if (superType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) superType;
System.out.println("父类泛型参数:" + pType.getActualTypeArguments()[0]);
}
}
}
Loading…
Cancel
Save