From 94eb7775ea963420c3f9018a0e5af41e96561081 Mon Sep 17 00:00:00 2001 From: GaoGeng <3123557312@qq.com> Date: Mon, 1 Jun 2026 09:15:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'W8'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- W8/Cache.java | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++ W8/Pair.java | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 108 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..7d9e7b7 --- /dev/null +++ b/W8/Cache.java @@ -0,0 +1,65 @@ +import java.util.HashMap; +import java.util.Map; + +public class Cache { + private Map cacheMap; + private int maxSize; + + public Cache() { + this.cacheMap = new HashMap<>(); + this.maxSize = Integer.MAX_VALUE; + } + + public Cache(int maxSize) { + this.cacheMap = new HashMap<>(); + this.maxSize = maxSize; + } + + public void put(K key, V value) { + if (cacheMap.size() >= maxSize) { + K firstKey = cacheMap.keySet().iterator().next(); + cacheMap.remove(firstKey); + } + cacheMap.put(key, value); + } + + public V get(K key) { + return cacheMap.get(key); + } + + public boolean containsKey(K key) { + return cacheMap.containsKey(key); + } + + public V remove(K key) { + return cacheMap.remove(key); + } + + public int size() { + return cacheMap.size(); + } + + public void clear() { + cacheMap.clear(); + } + + @Override + public String toString() { + return cacheMap.toString(); + } + + public static void main(String[] args) { + Cache cache = new Cache<>(3); + cache.put("A", 1); + cache.put("B", 2); + cache.put("C", 3); + System.out.println("Cache after adding A,B,C: " + cache); + + cache.put("D", 4); + System.out.println("Cache after adding D (maxSize=3): " + cache); + + System.out.println("Get B: " + cache.get("B")); + System.out.println("Contains C: " + cache.containsKey("C")); + System.out.println("Size: " + cache.size()); + } +} \ No newline at end of file diff --git a/W8/Pair.java b/W8/Pair.java new file mode 100644 index 0000000..428127f --- /dev/null +++ b/W8/Pair.java @@ -0,0 +1,43 @@ +public class Pair { + private K first; + private V second; + + public Pair(K first, V second) { + this.first = first; + this.second = second; + } + + public K getFirst() { + return first; + } + + public V getSecond() { + return second; + } + + public void setFirst(K first) { + this.first = first; + } + + public void setSecond(V second) { + this.second = second; + } + + public void swap() { + Object temp = first; + first = (K) second; + second = (V) temp; + } + + @Override + public String toString() { + return "(" + first + ", " + second + ")"; + } + + public static void main(String[] args) { + Pair pair = new Pair<>("Hello", 42); + System.out.println("Before swap: " + pair); + pair.swap(); + System.out.println("After swap: " + pair); + } +} \ No newline at end of file