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.
51 lines
1.3 KiB
51 lines
1.3 KiB
/**
|
|
* 泛型 Pair 类,表示一个键值对。
|
|
* @param <K> 键的类型
|
|
* @param <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;
|
|
}
|
|
|
|
public K getKey() {
|
|
return key;
|
|
}
|
|
|
|
public V getValue() {
|
|
return value;
|
|
}
|
|
|
|
/**
|
|
* 静态方法:交换 Pair 的键和值。
|
|
* @param pair 原始 Pair 对象
|
|
* @param <K> 原始键的类型
|
|
* @param <V> 原始值的类型
|
|
* @return 一个新的 Pair 对象,键值互换后的结果
|
|
*/
|
|
public static <K, V> Pair<V, K> swap(Pair<K, V> pair) {
|
|
// 如果输入为 null,可根据需求返回 null 或抛出异常(此处返回 null)
|
|
if (pair == null) {
|
|
return null;
|
|
}
|
|
return new Pair<>(pair.getValue(), pair.getKey());
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return "Pair{" + key + ", " + value + "}";
|
|
}
|
|
|
|
// 简单的测试示例
|
|
public static void main(String[] args) {
|
|
Pair<String, Integer> original = new Pair<>("age", 25);
|
|
System.out.println("Original: " + original);
|
|
|
|
Pair<Integer, String> swapped = Pair.swap(original);
|
|
System.out.println("Swapped: " + swapped);
|
|
}
|
|
}
|