I need the Cache class that keep the <TKey key, TValue value>
pairs. And it is desirable that TKey
can be any class that supports Serializable
interface and TValue
can be any class that supports Serializable
and my own ICacheable
interfaces.
There is another CacheItem
class that keeps <TKey key, TValue value>
pair.
I want the Cache class has the void add(CacheItem cacheItem)
method. Here is my code:
public class Cache<TKey extends Serializable,
TValue extends Serializable & ICacheable >
{
private Map<TKey, TValue> cacheStore =
Collections.synchronizedMap(new HashMap<TKey, TValue>());
public void add(TKey key, TValue value)
{
cacheStore.put(key, value);
}
public void add(CacheItem cacheItem)
{
TKey key = cacheItem.getKey();
//Do not compiles. Incompatible types. Required: TValue. Found: java.io.Serializable
TValue value = (TValue) cacheItem.getValue();
//I need to cast to (TValue) here to compile
//but it gets the Unchecked cast: 'java.io.Serializable' to 'TValue'
add(key, value);
}
}
In another file:
public class CacheItem<TKey extends Serializable,
TValue extends Serializable & ICacheable>
{
TKey key;
TValue value;
public TValue getValue()
{
return value;
}
public TKey getKey()
{
return key;
}
}
Is there anything I could do to avoid casting? Many thanks for answers.