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.
70 lines
1.6 KiB
70 lines
1.6 KiB
package w8;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class Pair {
|
|
|
|
// 泛型键值对 Pair
|
|
static class PairInner<K, V> {
|
|
private K key;
|
|
private V value;
|
|
|
|
public PairInner(K key, V value) {
|
|
this.key = key;
|
|
this.value = value;
|
|
}
|
|
|
|
// 交换方法
|
|
public PairInner<V, K> swap() {
|
|
return new PairInner<>(value, key);
|
|
}
|
|
|
|
public K getKey() {
|
|
return key;
|
|
}
|
|
|
|
public V getValue() {
|
|
return value;
|
|
}
|
|
}
|
|
|
|
// 泛型缓存 Cache
|
|
static class Cache<K, V> {
|
|
private Map<K, V> map = new HashMap<>();
|
|
|
|
public void put(K key, V value) {
|
|
map.put(key, value);
|
|
}
|
|
|
|
public V get(K key) {
|
|
return map.get(key);
|
|
}
|
|
|
|
public void remove(K key) {
|
|
map.remove(key);
|
|
}
|
|
|
|
public void clear() {
|
|
map.clear();
|
|
}
|
|
|
|
public boolean containsKey(K key) {
|
|
return map.containsKey(key);
|
|
}
|
|
}
|
|
|
|
// 主程序运行
|
|
public static void main(String[] args) {
|
|
// 测试 Pair
|
|
PairInner<String, Integer> pair = new PairInner<>("成绩", 95);
|
|
PairInner<Integer, String> swapped = pair.swap();
|
|
System.out.println("交换前:" + pair.getKey() + " " + pair.getValue());
|
|
System.out.println("交换后:" + swapped.getKey() + " " + swapped.getValue());
|
|
|
|
// 测试 Cache
|
|
Cache<String, String> cache = new Cache<>();
|
|
cache.put("姓名", "张三");
|
|
System.out.println("获取缓存:" + cache.get("姓名"));
|
|
}
|
|
}
|