繁体   English   中英

android java --key相同但containsKey返回false

[英]android java --key is same but containsKey return false

我必须将值放在LinkedHashMap中。 (因为,如果已有值,我想要排序和确定)

我认为如果String值像temptemp2一样,containsKey将返回true。 但是, testMap.put(temp2,8); 在跑。

我不知道为什么。 如果答案不正确,如何快速存储或访问值?

 public class TestClass{
        public String one;
        public String two;
        TestClass(String one, String two){
            this.one=one;
            this.two=two;
        }
    }
    public void testPersonWord(){
        LinkedHashMap<TestClass, Integer> testMap= new LinkedHashMap<>();
        TestClass temp= new TestClass("hdy","hello");
        testMap.put(temp,3);
        TestClass temp2= new TestClass("hdy","hello");
        if(testMap.containsKey(temp2)){
            testMap.replace(temp2,5);
        }else{
            testMap.put(temp2,8);
        }
    }

这是containKey方法。 hashCode用于比较,因此肯定两个对象的hashCode是不同的,因此不能相等。
您可以考虑使用原始键或使用TestClass.getOne()比较String。

/**
 * Returns <tt>true</tt> if this map contains a mapping for the
 * specified key.
 *
 * @param   key   The key whose presence in this map is to be tested
 * @return <tt>true</tt> if this map contains a mapping for the specified
 * key.
 */
public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

希望这可以帮助 !

暂无
暂无

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

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