简体   繁体   English

创建自定义多键HashMap

[英]Creating a custom multi-key HashMap

I have been trying to create a custom HashMap which contains 2 keys. 我一直在尝试创建一个包含2个键的自定义HashMap The user creates an object of my class with two parameters K and V . 用户使用两个参数KV创建我的类的对象。 The class is made of 2 HashMaps : natively extended <Integer, V> and key storage <K, Integer> . 该类由2个HashMaps :本地扩展的<Integer, V>和密钥存储<K, Integer> So basically, there are 2 keys for each value: K and Integer . 因此,基本上,每个值都有2个键: KInteger

When the user wants to get an item, he can retrieve both by using K key or Integer key. 当用户想要获取项目时,他可以使用K键或Integer键两者进行检索。 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 因此,例如,如果用户使用K则系统会在keyTable查找具有此类键的Integer,然后使用该Integer查找值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) { . 但是,我之前从未进行过参数化,因此我无法理解问题所在-我将Cannot perform instanceof check against type parameter V. Use instead its erasure Object instead since further generic type information will be erased at runtime if (key instanceof V) {

Is it even possible to achieve the system I want? 是否有可能实现我想要的系统?

You can't use parametrized types (K and V) in any operation performed at runtime (eg the instanceof operator). 在运行时执行的任何操作(例如instanceof运算符)中,都不能使用参数化类型(K和V)。 In Java all parametrization information is used at compile-time and then essentially removed from the compiled code. 在Java中,所有参数化信息都在编译时使用,然后从编译后的代码中删除。 This removal is referred to as type erasure. 此删除称为类型擦除。 1 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. 我建议您不要依赖于密钥的类型来确定要查找的HashMap,而是查看该密钥对于第一个HashMap是否有效,如果不是,请尝试第二个。 Keep in mind that K could be of type Integer, meaning that both key types could be identical. 请记住,K的类型可以是Integer,这意味着两个密钥类型可以相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM