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; } // 交换后 key/value 类型可能变化,所以返回新的 Pair public Pair swap() { return new Pair<>(this.value, this.key); } public static void main(String[] args) { Pair p = new Pair<>("Age", 25); Pair swapped = p.swap(); System.out.println(swapped.getKey() + "=" + swapped.getValue()); // 25=Age } }