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.
 
 

62 lines
2.1 KiB

import java.util.Optional;
public class Main {
public static void main(String[] args) {
System.out.println("===== Pair<K,V> 测试 =====");
testPair();
System.out.println();
System.out.println("===== Cache<K,V> 测试 =====");
testCache();
}
static void testPair() {
// 基本用法
Pair<String, Integer> p1 = new Pair<>("age", 20);
System.out.println("原始: " + p1);
Pair<Integer, String> p2 = p1.swap();
System.out.println("swap: " + p2);
// 不同类型组合
Pair<String, Boolean> p3 = new Pair<>("isStudent", true);
Pair<Boolean, String> p4 = p3.swap();
System.out.println("原始: " + p3 + " → swap: " + p4);
}
static void testCache() {
// 容量为 3 的 LRU 缓存
Cache<String, String> cache = new Cache<>(3);
cache.put("a", "Apple");
cache.put("b", "Banana");
cache.put("c", "Cherry");
System.out.println("初始状态: " + cache);
// 访问 a,使其成为最近使用
cache.get("a");
// 放入第4个,b 是最久未使用的,会被淘汰
cache.put("d", "Durian");
System.out.println("放入 d 后 (b 应被淘汰): " + cache);
System.out.println("b 是否存在: " + cache.containsKey("b")); // false
System.out.println("a 是否存在: " + cache.containsKey("a")); // true
// Optional 用法演示
Optional<String> val = cache.get("c");
val.ifPresent(v -> System.out.println("获取 c: " + v));
cache.get("x").ifPresentOrElse(
v -> System.out.println("获取 x: " + v),
() -> System.out.println("获取 x: 不存在(缓存未命中)")
);
// 整数缓存
Cache<Integer, Double> numCache = new Cache<>(2);
numCache.put(1, 3.14);
numCache.put(2, 2.71);
numCache.put(3, 1.41); // 1 被淘汰
System.out.println("数值缓存: " + numCache);
System.out.println("key=1 存在: " + numCache.containsKey(1)); // false
}
}