diff --git a/w8/Pair.java b/w8/Pair.java new file mode 100644 index 0000000..fe86dad --- /dev/null +++ b/w8/Pair.java @@ -0,0 +1,111 @@ +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +public class Pair { + private K first; + private V second; + + public Pair(K first, V second) { + this.first = first; + this.second = second; + } + + public K getFirst() { + return first; + } + + public void setFirst(K first) { + this.first = first; + } + + public V getSecond() { + return second; + } + + public void setSecond(V second) { + this.second = second; + } + + /** + * 安全地交换 Pair 中的两个元素。 + * 注意:这将创建一个新的 Pair 对象并返回,而不是修改原对象。 + */ + public Pair swapped() { + return new Pair<>(this.second, this.first); + } + + @Override + public String toString() { + return "Pair{first=" + first + ", second=" + second + '}'; + } + + public static 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 void remove(K key) { + cache.remove(key); + } + + public int size() { + return cache.size(); + } + + // 为了能够通过反射获取泛型信息,需要让子类继承它 + public Class getKeyType() { + return getGenericType(0); + } + + public Class getValueType() { + return getGenericType(1); + } + + private Class getGenericType(int index) { + Type genericSuperclass = this.getClass().getGenericSuperclass(); + if (genericSuperclass instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + if (index >= 0 && index < actualTypeArguments.length) { + Type type = actualTypeArguments[index]; + if (type instanceof Class) { + return (Class) type; + } + } + } + return Object.class; + } + } + + public static void main(String[] args) { + // 演示 Pair 的用法 + Pair pair = new Pair<>("Hello", 100); + System.out.println("Original Pair: " + pair); + Pair swappedPair = pair.swapped(); + System.out.println("Swapped Pair: " + swappedPair); + + // 演示 Cache 的用法和泛型类型获取 + // 必须创建一个匿名子类才能保留泛型信息供反射使用 + Cache stringIntCache = new Cache() {}; + stringIntCache.put("answer", 42); + stringIntCache.put("year", 2024); + + System.out.println("\n--- Cache Demo ---"); + System.out.println("Key type: " + stringIntCache.getKeyType().getSimpleName()); + System.out.println("Value type: " + stringIntCache.getValueType().getSimpleName()); + System.out.println("Size: " + stringIntCache.size()); + System.out.println("Value for 'answer': " + stringIntCache.get("answer")); + } +} \ No newline at end of file