public class Pair { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } // swap方法:交换key和value的位置 public Pair swap() { return new Pair<>(this.value, this.key); } @Override public String toString() { return "Pair{" + "key=" + key + ", value=" + value + '}'; } // 测试方法 public static void main(String[] args) { Pair pair = new Pair<>("age", 25); System.out.println("原始Pair: " + pair); Pair swapped = pair.swap(); System.out.println("交换后Pair: " + swapped); } }