I am trying to make a singleton like the following, but I keep getting a warning. If possible, I don't want suppress warning. Is there a way to do it?
For now, I don't want to think about the thread-safety. I just want to pass this warning.
public interface Storage<K, V> {
public void put(K key, V value);
public V get(K key);
}
public static class DefaultStorage<K, V> implements Storage<K, V> {
private Map<Object, Object> map = new ConcurrentHashMap<Object, Object>();
private static DefaultStorage<K, V> defaultStorage;
private DefaultStorage() {
//
}
public static DefaultStorage<?, ?> getInstance() {
if (defaultStorage== null) {
defaultStorage= new DefaultStorage();
}
return defaultStorage;
}
}
Thanks.
The variable
defaultStorageinDefaultStorageonly exists once in every instance of aDefaultStoragecombined. At runtime there's only one actual class, and one static variable. So, the variable will simultaneously be aDefaultStorage<K1, V1>, aDefaultStorage<K2, V2>, aDefaultStorage<K3, V3>, and so on. So, one class will storeStringsin it, another will storeBigDecimals, and anotherX501Principals. This subverts type-safety.The warning is that you are storing an instance of a raw type,
new DefaultStorage(), in a variable declared asDefaultStorage<K, V>.From Angelika Langer's Generics FAQ,