// 泛型键值对类 Pair public class Pair { // 私有成员变量 private final K key; private final V value; // 构造方法 public Pair(K key, V value) { this.key = key; this.value = value; } // getter 方法 public K getKey() { return key; } public V getValue() { return value; } /** * 静态泛型方法:交换键值 * 传入 Pair,返回 交换后的 Pair */ public static Pair swap(Pair pair) { // 空值防护 if (pair == null) { return null; } // 新对象:把原值当key,原key当value return new Pair<>(pair.getValue(), pair.getKey()); } // 重写toString,方便打印 @Override public String toString() { return "[" + key + ", " + value + "]"; } }