# What is the better way to retrieve value from this cache implementaion?

I have the following methods in CacheUtil class

public void addCacheEntry(String key, Serializable entry) {
}

public void removeCacheEntry(String key) {
//remove from cache
}

public Serializable getCacheEntry(String key) {
Serializable entry = // get from cache
return entry;
}


And in the class where I use the cache, I have the following methods,

public List<String> fetchList() {
List<String> aList = (List<String>) CacheUtil.getInstance().getCacheEntry("aList"); //IDE warns of unchecked casting
if(aList == null) {
aList = fetchFromDB():
}
}


How could I have avoided the warning of unchecked cast? I can not change the methods in cache to store lists explicitly, as I want to store anything that is serializable in cache and that is just a library.

I believe there is a better way to do it.

-

You could change your CacheUtil class to the following:

public class CacheUtil {
...
public void addCacheEntry(String key, Serializable entry) {
}

public void removeCacheEntry(String key) {
//remove from cache
}

public <T extends Serializable> T getCacheEntry(String key) {
T entry = // get from cache (probably needs a cast to T)
return entry;
}
}


which would allow you to get cached entries by type T without a cast:

    public List<String> fetchList() {
ArrayList<String> aList = CacheUtil.getInstance().getCacheEntry("aList");
if(aList == null) {
aList = fetchFromDB():
}
}


Notice that I was required to use ArrayList, because List is not Serializable on its own. You could take this one step farther and have getCacheEntry() return T without extends:

    public <T> T getCacheEntry(String key) {
T entry = // get from cache (may need a cast)
return entry;
}


But Im not sure I'd take that leap.

-
Hi @johncari, thanks for the suggestion. Changing the method signature in CacheUtil to <T extends Serializable>, moves the unchecked cast warning to CacheUtil class (when casting entry to T). Is there anyway i can avoid that too? That warning is not bad? – Senthil Kumar Nov 28 '12 at 3:51
You could add this to the method to avoid the warning: @SuppressWarnings("unchecked") – John Ericksen Nov 28 '12 at 15:58
@SenthilKumar By moving the cast elsewhere and adding SuppressWarnings you wan't improve it. There are two problems: 1. You need class CacheUtil<T extends Serializable> so you can create type-safe caches (look at List or any such collection). 2. And then you can't use CacheUtil.getInstance(), which is a good thing as such a static method prevents you from using multiple caches. – maaartinus Aug 19 '14 at 4:16