public class Pair { private K key; private V value; // 构造方法 public Pair(K key, V value) { this.key = key; this.value = value; } // 交换 key 和 value 的方法(注意:交换后类型会变为 Pair) public Pair swap() { return new Pair<>(this.value, this.key); } // Getter 和 Setter public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } @Override public String toString() { return "Pair{" + "key=" + key + ", value=" + value + '}'; } // 测试 public static void main(String[] args) { Pair pair = new Pair<>("age", 20); System.out.println("原Pair: " + pair); Pair swappedPair = pair.swap(); System.out.println("交换后: " + swappedPair); } }