Browse Source

W8-徐景旺-202414010701

main
XuJingwang 2 months ago
parent
commit
f095bf1e79
  1. 31
      W8/Cache.java
  2. 37
      W8/Pair.java

31
W8/Cache.java

@ -0,0 +1,31 @@
import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
// 使用 HashMap 作为底层存储容器
private Map<K, V> storage = new HashMap<>();
public void put(K key, V value) {
storage.put(key, value);
}
public V get(K key) {
return storage.get(key);
}
public void remove(K key) {
storage.remove(key);
}
public boolean containsKey(K key) {
return storage.containsKey(key);
}
public int size() {
return storage.size();
}
public static void main(String[] args) {
Cache<String, String> userCache = new Cache<>();
userCache.put("user:1001", "Alice");
userCache.put("user:1002", "Bob");
String user1 = userCache.get("user:1001");
System.out.println("获取到的用户: " + user1);
if (userCache.containsKey("user:1002")) {
System.out.println("用户 1002 在缓存中");
}
}
}

37
W8/Pair.java

@ -0,0 +1,37 @@
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 void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Pair<V, K> swap() {
return new Pair<>(this.value, this.key);
}
@Override
public String toString() {
return "(" + key + ", " + value + ")";
}
public static void main(String[] args) {
Pair<String, Integer> original = new Pair<>("Age", 25);
System.out.println("原始 Pair: " + original);
// 调用 swap 方法
Pair<Integer, String> swapped = original.swap();
System.out.println("交换后 Pair: " + swapped);
}
}
Loading…
Cancel
Save