Strange Java HashMap behavior – no matching object found

When I tried in Java util. When I found a key in HashMap, I encountered some strange behavior. I think I missed something The code snippet is basically:

HashMap<Key,Value> data = ...
Key k1 = ...

Value v = data.get(k1);
boolean bool1 = data.containsKey(k1);
for (Key k2 : data.keySet()) {
    boolean bool2 = k1.equals(k2);
    boolean bool3 = k2.equals(k1);
    boolean bool4 = k1.hashCode() == k2.hashCode();
    break;
}

That strange loop is because for a particular execution, I happen to know that the data contains only one item at this time and it is K1, and actually bool2, bool3 and bool4 will be evaluated as true in this execution However, bool1 will be evaluated as false and V will be null

Now, this is part of a larger program - I can't reproduce the error on a smaller sample - but in my opinion, no matter what the rest of the program does, this behavior should not happen

Edit: I have manually verified that the hash code does not change between the time when the object is inserted into the map and the query time I will continue to check the site, but are there any other options?

Solution

This behavior occurs if the hash code of the key changes after inserting the map

Here is an example of the behavior you described:

public class Key
{
int hashCode = 0;

@Override
public int hashCode() {
    return hashCode;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Key other = (Key) obj;
    return hashCode == other.hashCode;
}

public static void main(String[] args) throws Exception {
    HashMap<Key,Integer> data = new HashMap<Key,Integer>();
    Key k1 = new Key();
    data.put(k1,1);

    k1.hashCode = 1;

    boolean bool1 = data.containsKey(k1);
    for (Key k2 : data.keySet()) {
        boolean bool2 = k1.equals(k2);
        boolean bool3 = k2.equals(k1);
        boolean bool4 = k1.hashCode() == k2.hashCode();

        System.out.println("bool1: " + bool1);
        System.out.println("bool2: " + bool2);
        System.out.println("bool3: " + bool3);
        System.out.println("bool4: " + bool4);

        break;
    }
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>