Xingzhimeng 2 months ago
parent
commit
f9493ba5a3
  1. BIN
      w8/Cache.class
  2. 62
      w8/Cache.java
  3. BIN
      w8/Pair.class
  4. 21
      w8/Pair.java

BIN
w8/Cache.class

Binary file not shown.

62
w8/Cache.java

@ -0,0 +1,62 @@
import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
// 用 HashMap 存储缓存数据
private final Map<K, V> cache;
// 构造方法:初始化缓存
public Cache() {
cache = new HashMap<>();
}
// 存入缓存
public void put(K key, V value) {
cache.put(key, value);
}
// 从缓存读取
public V get(K key) {
return cache.get(key);
}
// 判断缓存是否存在某个 key
public boolean containsKey(K key) {
return cache.containsKey(key);
}
// 移除缓存
public void remove(K key) {
cache.remove(key);
}
// 清空缓存
public void clear() {
cache.clear();
}
// 获取缓存大小
public int size() {
return cache.size();
}
// 测试 main 方法
public static void main(String[] args) {
Cache<String, Integer> studentScore = new Cache<>();
// 存入数据
studentScore.put("张三", 90);
studentScore.put("李四", 85);
// 读取数据
System.out.println("张三的分数:" + studentScore.get("张三"));
System.out.println("缓存大小:" + studentScore.size());
// 判断是否存在
System.out.println("是否包含李四:" + studentScore.containsKey("李四"));
// 移除数据
studentScore.remove("李四");
System.out.println("移除后缓存大小:" + studentScore.size());
}
}

BIN
w8/Pair.class

Binary file not shown.

21
w8/Pair.java

@ -0,0 +1,21 @@
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public void swap() {
K temp = key;
key = (K)value;
value = (V)temp;
}
public K getKey() { return key; }
public V getValue() { return value; }
public static void main(String[] args) {
Pair<Object, Object> pair = new Pair<>("Name", 18);
System.out.println("Before swap: key=" + pair.getKey() + ", value=" + pair.getValue());
pair.swap();
System.out.println("After swap: key=" + pair.getKey() + ", value=" + pair.getValue());
}
}
Loading…
Cancel
Save