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.
 
 

38 lines
849 B

/**
* 泛型 Pair 类,用于存储两个相关联的对象
* @param <K> 键类型
* @param <V> 值类型
*/
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 的值(注意:仅适用于可互换类型的场景)
* 注意:如果 K 和 V 类型不同,交换后可能语义不一致
*/
public void swap() {
// 使用 Object 临时存储,再交换
Object temp = key;
key = value;
value = (V) temp; // 强转,需确保类型兼容
}
@Override
public String toString() {
return "(" + key + ", " + value + ")";
}
}