Java ';等于();返回false,但在映射中找到对象

Java ';等于();返回false,但在映射中找到对象,java,map,equals,hashcode,Java,Map,Equals,Hashcode,我在乱搞一些hashCode+equals+Map的东西,发现了一些东西。。。奇怪 片段如下所示: class Obj { String n; Obj(String n) {this.n = n;} public int hashCode() {return 0;} public boolean equals(Object o) {return false;} // no instance of this class

我在乱搞一些hashCode+equals+Map的东西,发现了一些东西。。。奇怪

片段如下所示:

class Obj {
    String n;
    Obj(String n) {this.n = n;}

    public int hashCode() {return 0;}
    public boolean equals(Object o) {return false;} // no instance of this class 
                                                    // equals any other instance

}
然后我做了这样的事情:

    java.util.Map<Obj,String> map = new java.util.HashMap<Obj,String>();
    Obj o1 = new Obj("1");
    Obj o11 = new Obj("1");
    Obj o2 = new Obj("2");

    map.put(o1,"val 1");
    map.put(o11,"val 2");
    map.put(o2,"val 3");

    p("size = " + map.size()); // obviously 3
    p(map.get(new Obj("1"))); // obviously null     
    p(map.get(o1)); // ...
java.util.Map=new java.util.HashMap();
Obj o1=新Obj(“1”);
Obj o11=新Obj(“1”);
Obj o2=新Obj(“2”);
地图放置(o1,“val 1”);
地图放置(o11,“val 2”);
地图放置(o2,“val 3”);
p(“size=“+map.size());//显然是3
p(map.get(新对象(“1”));//明显无效
p(map.get(o1));/。。。
最后一行是奇怪的部分。最后一行返回
val 1
。怎么会?
equals
方法始终返回
false
。这是因为在调用
equals
之前使用了
=
运算符吗


感谢您提供的见解。

哈希映射实现检查键的==和equals相等性。 (如果哈希代码相同)

在中,
get
方法是:

public V get(Object key) {
    if (key == null)
        return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}
public V get(对象键){
if(key==null)
返回getForNullKey();
int hash=hash(key.hashCode());
for(条目e=表[indexFor(hash,table.length)];
e!=null;
e=e.next){
对象k;
如果(e.hash==hash&((k=e.key)==key | | key.equals(k)))
返回e.value;
}
返回null;
}
如果(e.hash==hash&((k=e.key)==key | | key.equals(k))行在调用
equals之前确实使用
==
比较了密钥。这就是你消除平等的尝试失败的原因