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) {
    //add to cache
}

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&lt;String&gt; fetchList() {
   List&lt;String&gt; aList = (List&lt;String&gt;) CacheUtil.getInstance().getCacheEntry("aList"); //IDE warns of unchecked casting
   if(aList == null) {
     aList = fetchFromDB():
     CacheUtil.getInstance().addCacheEntry("aList", new ArrayList&lt;String&gt;(aList));
   }
}


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) {
        //add to cache
    }

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

    public &lt;T extends Serializable&gt; 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&lt;String&gt; fetchList() {
       ArrayList&lt;String&gt; aList = CacheUtil.getInstance().getCacheEntry("aList");
       if(aList == null) {
         aList = fetchFromDB():
         CacheUtil.getInstance().addCacheEntry("aList", new ArrayList&lt;String&gt;(aList));
       }
    }


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 &lt;T&gt; T getCacheEntry(String key) {
       T entry = // get from cache (may need a cast)
       return entry;
    }


But Im not sure I'd take that leap.