Search code examples
javahashmapextend

Creating a custom multi-key HashMap


I have been trying to create a custom HashMap which contains 2 keys. The user creates an object of my class with two parameters K and V. The class is made of 2 HashMaps: natively extended <Integer, V> and key storage <K, Integer>. So basically, there are 2 keys for each value: K and Integer.

When the user wants to get an item, he can retrieve both by using K key or Integer key. So, for example, if user uses K then the system looks up in keyTable for an Integer with such key and then uses that Integer to find the value V

public class KeyMap<K, V> extends ConcurrentHashMap<Integer, V> {

    private HashMap<K, Integer> keyTable = new HashMap<K, Integer>(10);

    @Override
    public V get(Object key) {
        if (key instanceof V) {
            return super.get(keyTable.get(key));
        }
        return super.get(key);
    }

}

However, I am have never done parameterization before therefore I cannot understand what's the problem - I am getting Cannot perform instanceof check against type parameter V. Use instead its erasure Object instead since further generic type information will be erased at runtime on line if (key instanceof V) {.

Is it even possible to achieve the system I want?


Solution

  • You can't use parametrized types (K and V) in any operation performed at runtime (e.g the instanceof operator). In Java all parametrization information is used at compile-time and then essentially removed from the compiled code. This removal is referred to as type erasure. 1

    I suggest you don't rely on the type of the key to determine which HashMap to look in and instead see if the key is a valid key for the first HashMap, and if not, try just the second. Keep in mind that K could be of type Integer, meaning that both key types could be identical.