You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.4 KiB
40 lines
1.4 KiB
package w8;
|
|
public class Main {
|
|
public static void main(String[] args) throws InterruptedException {
|
|
// Pair test
|
|
Pair<String, Integer> pair = new Pair<>("age", 25);
|
|
System.out.println("Original: " + pair);
|
|
System.out.println("Swap: " + pair.swap());
|
|
|
|
// Cache test
|
|
Cache<String, String> cache = new Cache<>(3000);
|
|
cache.put("name", "Ahmed");
|
|
System.out.println("Cache get: " + cache.get("name"));
|
|
}
|
|
}
|
|
|
|
class Pair<K, V> {
|
|
private K key;
|
|
private V value;
|
|
public Pair(K key, V value) { this.key = key; this.value = value; }
|
|
public Pair<V, K> swap() { return new Pair<>(value, key); }
|
|
public String toString() { return "Pair{" + key + "," + value + "}"; }
|
|
}
|
|
|
|
class Cache<K, V> {
|
|
private java.util.HashMap<K, CacheEntry<V>> 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<V> entry = cache.get(key);
|
|
if (entry == null || (entry.expireTime > 0 && System.currentTimeMillis() > entry.expireTime)) return null;
|
|
return entry.value;
|
|
}
|
|
private static class CacheEntry<V> {
|
|
V value; long expireTime;
|
|
CacheEntry(V v, long e) { value = v; expireTime = e; }
|
|
}
|
|
}
|