import java.util.HashMap; import java.util.Map; // 整个作业只需要这一个文件! // 泛型键值对 Pair static class Pair { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } // 交换方法 public Pair swap() { return new Pair<>(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) { // 测试 void main(String[] args) { // 测试 Pair Pair pair = new Pair<>("成绩", 95); Pair 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("姓名")); }