Avoiding unsafe cast for generic situation involving runtime passing of class

Posted by Bart van Heukelom on Stack Overflow See other posts from Stack Overflow or by Bart van Heukelom
Published on 2010-12-28T13:08:20Z Indexed on 2010/12/29 1:53 UTC
Read the original article Hit count: 625

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics