package w8; import java.util.HashMap; import java.util.Map; public class Pair { // 泛型键值对 Pair static class PairInner { private K key; private V value; public PairInner(K key, V value) { this.key = key; this.value = value; } // 交换方法 public PairInner swap() { return new PairInner<>(value, key); } public K getKey() { return key; } public V getValue() { return value; } } // 泛型缓存 Cache static class Cache { private Map map = new HashMap<>(); public void put(K key, V value) { map.put(key, value); } public V get(K key) { return map.get(key); } public void remove(K key) { map.remove(key); } public void clear() { map.clear(); } public boolean containsKey(K key) { return map.containsKey(key); } } // 主程序运行 public static void main(String[] args) { // 测试 Pair PairInner pair = new PairInner<>("成绩", 95); PairInner swapped = pair.swap(); System.out.println("交换前:" + pair.getKey() + " " + pair.getValue()); System.out.println("交换后:" + swapped.getKey() + " " + swapped.getValue()); // 测试 Cache Cache cache = new Cache<>(); cache.put("姓名", "张三"); System.out.println("获取缓存:" + cache.get("姓名")); } }