Java HashMap get works but containsKey does not

后端 未结 9 1300
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 05:41

I am trying to locate a key in a HashMap. I can print the selected key by using \'get\' but when I use \'containsKey\' in an if statement, it is not found.

I KNOW

9条回答
  •  情书的邮戳
    2020-12-06 06:19

    As descibed here, you have to override the equals(Object) method.

    The reason why get(Object) is working is, that HashMap will calculate the Hash for your Location class and returns the Object the hascode points to.

    containsKey(Object) calculates the hash key and gets the object the hash is pointed to. The object from the HashMap will compare to the Object you put in. For these comparison the equals method is used. When you do not override he equals method, true is returned, when the object reference to the same instance.

    From HashMap

    /** 
     * Check for equality of non-null reference x and possibly-null y. 
     */
    static boolean eq(Object x, Object y) {
        return x == y || x.equals(y);
    }
    

    From Object

    public boolean equals(Object obj) {
        return (this == obj);
        }
    

    From the javadoc of equals

    The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

提交回复
热议问题