2 changed files with 108 additions and 0 deletions
@ -0,0 +1,65 @@ |
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
|
|||
public class Cache<K, V> { |
|||
private Map<K, V> 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<String, Integer> 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()); |
|||
} |
|||
} |
|||
@ -0,0 +1,43 @@ |
|||
public class Pair<K, V> { |
|||
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<String, Integer> pair = new Pair<>("Hello", 42); |
|||
System.out.println("Before swap: " + pair); |
|||
pair.swap(); |
|||
System.out.println("After swap: " + pair); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue