Skip to content

Instantly share code, notes, and snippets.

@serdarmumcu
Created July 31, 2020 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serdarmumcu/b521cefdf66e1661d16726c63a59594d to your computer and use it in GitHub Desktop.
Save serdarmumcu/b521cefdf66e1661d16726c63a59594d to your computer and use it in GitHub Desktop.
Random Cache Implementation Java
package com.yazilimmimari.hackerrank;
import java.util.*;
public class RandomCache<S,T> {
HashMap<S,T> cache;
int capacity;
RandomCache(int capacity) {
cache = new HashMap<>(capacity);
this.capacity = capacity;
}
T get(S key) {
if(!cache.containsKey(key))
return null;
return cache.get(key);
}
void put(S key, T value) {
if(cache.containsKey(key))
{
cache.replace(key, value);
return;
}
else if(cache.size() == capacity)
{
//List<S> list = (List<S>)Arrays.asList(cache.keySet().toArray());
//Collections.shuffle(list);
//cache.remove(list.get(0));
Random generator = new Random();
T[] keys = (T [])cache.keySet().toArray();
T randomKey = keys[generator.nextInt(keys.length)];
cache.remove(randomKey);
}
cache.put(key,value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment