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