2 changed files with 68 additions and 0 deletions
@ -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 在缓存中"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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…
Reference in new issue