You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

23 lines
648 B

public class Pair<K, V> {
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<V, K>
public Pair<V, K> swap() {
return new Pair<>(this.value, this.key);
}
public static void main(String[] args) {
Pair<String, Integer> p = new Pair<>("Age", 25);
Pair<Integer, String> swapped = p.swap();
System.out.println(swapped.getKey() + "=" + swapped.getValue()); // 25=Age
}
}