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.
 
 

69 lines
1.6 KiB

import java.util.HashMap;
import java.util.Map;
// 整个作业只需要这一个文件!
// 泛型键值对 Pair
static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
// 交换方法
public Pair<V, K> swap() {
return new Pair<>(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) {
// 测试 void main(String[] args) {
// 测试 Pair
Pair<String, Integer> pair = new Pair<>("成绩", 95);
Pair<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("姓名"));
}