【发布时间】:2019-10-31 10:59:52
【问题描述】:
import java.util.HashMap;
import java.util.Map;
class Geek
{
public String name;
public int id;
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object obj)
{
// checking if both the object references are
// referring to the same object.
if(this == obj)
return true;
// it checks if the argument is of the
// type Geek by comparing the classes
// of the passed argument and this object.
// if(!(obj instanceof Geek)) return false; ---> avoid.
if(obj == null || obj.getClass()!= this.getClass())
return false;
// type casting of the argument.
Geek geek = (Geek) obj;
// comparing the state of argument with
// the state of 'this' Object.
System.out.println("equals method ....."+(geek.name == this.name && geek.id == this.id));
return (geek.name == this.name && geek.id == this.id);
}
int counter = 0;
@Override
public int hashCode()
{
// We are returning the Geek_id
// as a hashcode value.
// we can also return some
// other calculated value or may
// be memory address of the
// Object on which it is invoked.
// it depends on how you implement
// hashCode() method.
++counter;
System.out.println("counter ::>>> "+counter);
return counter;
}
驱动代码:
public static void main (String[] args)
{
Map<Geek, Integer> map = new HashMap<>();
// creating the Objects of Geek class.
Geek g1 = new Geek("aa", 1);
Geek g2 = new Geek("aa", 1);
map.put(g1, g1.id);
map.put(g2, g2.id);
map.forEach((k,v) -> {
System.out.println("key = "+k + "\n value = "+v);
});
/* else
System.out.println("Both Objects are not equal. "); */
}
在这里,我重写了hashCode() 方法,但地图仍然只包含一个对象g2。考虑到我的哈希码每次都返回不同的整数,为什么 HashMap 不存储两个对象?
即使我的equals() 方法对同一个对象返回true,为什么HashMap 没有存储两个对象?有人可以在这方面指导我吗?
【问题讨论】:
-
虽然在这种情况下您的
hashCode方法实际上确实为不同的对象返回相同的哈希码,但HashMap使用equals来比较不同哈希码的对象并非不可能,如果对象应该碰巧落在同一个哈希表桶中。您故意在此处尝试破坏地图,因此您不应该期望符合逻辑的行为。