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.
41 lines
897 B
41 lines
897 B
// 泛型键值对类 Pair<K,V>
|
|
public class Pair<K, V> {
|
|
// 私有成员变量
|
|
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<A,B>,返回 交换后的 Pair<B,A>
|
|
*/
|
|
public static <A, B> Pair<B, A> swap(Pair<A, B> pair) {
|
|
// 空值防护
|
|
if (pair == null) {
|
|
return null;
|
|
}
|
|
// 新对象:把原值当key,原key当value
|
|
return new Pair<>(pair.getValue(), pair.getKey());
|
|
}
|
|
|
|
// 重写toString,方便打印
|
|
@Override
|
|
public String toString() {
|
|
return "[" + key + ", " + value + "]";
|
|
}
|
|
|
|
}
|
|
|