From f095bf1e79647d6f2cc82d2ca3028099d2021c31 Mon Sep 17 00:00:00 2001 From: XuJingwang Date: Wed, 29 Apr 2026 15:32:12 +0800 Subject: [PATCH] =?UTF-8?q?W8-=E5=BE=90=E6=99=AF=E6=97=BA-202414010701?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- W8/Cache.java | 31 +++++++++++++++++++++++++++++++ W8/Pair.java | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 W8/Cache.java create mode 100644 W8/Pair.java diff --git a/W8/Cache.java b/W8/Cache.java new file mode 100644 index 0000000..955d23a --- /dev/null +++ b/W8/Cache.java @@ -0,0 +1,31 @@ +import java.util.HashMap; +import java.util.Map; +public class Cache { + // 使用 HashMap 作为底层存储容器 + private Map 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 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 在缓存中"); + } + } +} diff --git a/W8/Pair.java b/W8/Pair.java new file mode 100644 index 0000000..9078efd --- /dev/null +++ b/W8/Pair.java @@ -0,0 +1,37 @@ +public class Pair { + 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 swap() { + return new Pair<>(this.value, this.key); + } + @Override + public String toString() { + return "(" + key + ", " + value + ")"; + } + public static void main(String[] args) { + Pair original = new Pair<>("Age", 25); + System.out.println("原始 Pair: " + original); + + // 调用 swap 方法 + Pair swapped = original.swap(); + System.out.println("交换后 Pair: " + swapped); + } +} \ No newline at end of file