Avoiding unsafe cast for generic situation involving runtime passing of class
- by Bart van Heukelom
public class AutoKeyMap<K,V> {
public interface KeyGenerator<K> {
public K generate();
}
private KeyGenerator<K> generator;
public AutoKeyMap(Class<K> keyType) {
// WARNING: Unchecked cast from AutoKeyMap.IntKeyGen to AutoKeyMap.KeyGenerator<K>
if (keyType == Integer.class) generator = (KeyGenerator<K>) new IntKeyGen();
else throw new RuntimeException("Cannot generate keys for " + keyType);
}
public void put(V value) {
K key = generator.generate();
...
}
private static class IntKeyGen implements KeyGenerator<Integer> {
private final AtomicInteger ai = new AtomicInteger(1);
@Override public Integer generate() {
return ai.getAndIncrement();
}
}
}
In the code sample above, what is the correct way to prevent the given warning, without adding a @SuppressWarnings, if any?