From db87aee2d6e2c6a8a0b2a0a78861c6cacbd7e786 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?SALAH=20ABDULLAH=E9=98=BF=E5=B1=B1?= <2040abdullah@gmail.com> Date: Thu, 14 May 2026 11:22:47 +0800 Subject: [PATCH] w55 --- src/w8/Main.java | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/w8/Main.java diff --git a/src/w8/Main.java b/src/w8/Main.java new file mode 100644 index 0000000..81b580f --- /dev/null +++ b/src/w8/Main.java @@ -0,0 +1,40 @@ +package w8; + public class Main { + public static void main(String[] args) throws InterruptedException { + // Pair test + Pair pair = new Pair<>("age", 25); + System.out.println("Original: " + pair); + System.out.println("Swap: " + pair.swap()); + + // Cache test + Cache cache = new Cache<>(3000); + cache.put("name", "Ahmed"); + System.out.println("Cache get: " + cache.get("name")); + } +} + +class Pair { + private K key; + private V value; + public Pair(K key, V value) { this.key = key; this.value = value; } + public Pair swap() { return new Pair<>(value, key); } + public String toString() { return "Pair{" + key + "," + value + "}"; } +} + +class Cache { + private java.util.HashMap> cache = new java.util.HashMap<>(); + private long defaultExpireTime; + public Cache(long t) { this.defaultExpireTime = t; } + public void put(K key, V value) { + cache.put(key, new CacheEntry<>(value, defaultExpireTime > 0 ? System.currentTimeMillis() + defaultExpireTime : 0)); + } + public V get(K key) { + CacheEntry entry = cache.get(key); + if (entry == null || (entry.expireTime > 0 && System.currentTimeMillis() > entry.expireTime)) return null; + return entry.value; + } + private static class CacheEntry { + V value; long expireTime; + CacheEntry(V v, long e) { value = v; expireTime = e; } + } +} \ No newline at end of file