The value found from the card does not match identical hash codes and is equal to

Perhaps not the best name, please edit it.

This is the code I have.

import java.util.Map;
import java.util.HashMap;

public class App {
    public static void main(String[] args) {
        final Foo foo = new Foo();
        final Foo bar = new Foo();

        System.out.println("foo equals foo: " + foo.equals(foo));
        System.out.println("foo equals bar: " + foo.equals(bar));

        System.out.println("foo hashcode: " + foo.hashCode());
        System.out.println("bar hashcode: " + bar.hashCode());

        final Map<Foo, Integer> foos = new HashMap<Foo, Integer>();
        foos.put(foo, -99);

        System.out.println("foos.getfoo: " + foos.get(foo));
        System.out.println("foos.getbar: " + foos.get(bar));
    }    
}

class Foo {
    @Override
    public boolean equals(Object o) {
        return false;
    }

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

So, before reading further, you can guess what will be displayed for the next operator 2?

System.out.println("foos.getfoo: " + foos.get(foo));
System.out.println("foos.getbar: " + foos.get(bar));

I would expect to see:

null
null

since even if the hash codes really match, Fooit will always return false for any instance , so using the instance Fooas a key on the map should not be useful at all.

However, the conclusion:

:~ $ javac App.java
:~ $ java App
foo equals foo: false
foo equals bar: false
foo hashcode: -1
bar hashcode: -1
foos.getfoo: -99
foos.getbar: null

What am I missing? How is -99 extracted when I use an object with hashcode -1 and is NOT equal to myself, but then get null later with the same type of instance, which is also NOT equal to what I have on the Map, and also has hashcode -1?

+4
1

get() HashMap , equals():

Node<K,V> getNode(int hash, Object key), V get(Object key):

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

:

(k = first.key) == key

(k = e.key) == key

.


, equals(), , :

class Foo {
    @Override
    public boolean equals(Object o) {
        return false;
    }    
   ...
}

, x.equals() .

, equals(), , , , .

+7

Source: https://habr.com/ru/post/1682720/


All Articles