-1

I'm trying to see if modifying a custom cache implementation to use generics in the LinkedHashMap instead of LinkedHashMap<Object, Object>. I presume the <Object, Object> is suitable, but what is the best practice? Does the use of generics make sense?

public class Cache extends LinkedHashMap<Object, Object>{
    private static final long serialVersionUID = -4297992703249995219L;
    private final int cacheSize;
    public Cache(int size){
        super(size + 1, .75f, true); 
        this.cacheSize=size;
    }

     protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
        return size() > cacheSize;
     }
}

public class Main {
    public static void main(String[] args) {
        Cache cache = new Cache(2);
        cache.put(1, "one");
        cache.put(2, "two");

        for(Entry<Object, Object> entry : cache.entrySet()){
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
}
4

1 回答 1

2

If you want your Cache class to be generic as well, declare it as such:

public class Cache<K,V> extends LinkedHashMap<K,V>{

Then you can declare, for instance,

Cache<Integer,String> cache = new Cache<>();
...
cache.put(1,"String 1");
cache.put(2,"String 2");

However, if what you want is a heterogeneous collection, where you can do

cache.put(1,"String 1");
cache.put(new MyObject1(), new SomeOtherObject());

Then this is stretching the capabilities of the Java generic system. You will need to use <Object,Object> and save a class tag with each entry so you can know the runtime type when you need it.

于 2013-07-19T01:28:17.427 回答