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()); } }