【发布时间】:2017-12-16 15:53:29
【问题描述】:
我有一个程序来搜索键以打印哈希图中的值。但是我对键和值的输入是用户定义的对象。现在当我将输入key 等同于key1 时,为什么程序中对象key 和key1 的哈希码看起来不同,尽管返回类型相同,即。 NameInit,String str="abc" 和 abc 的哈希码在哪里返回相等?如何在程序中检查key和key1是否相等?我在类型转换为Object 类之后尝试了Objects.equals(key,key1),但仍然没有工作。我已经看到类似的问题,例如[this question][1] 中讨论哈希码相等性的问题,但又该如何做在我的例子中这些对象的相等性。请帮忙。
NameInit 类
public class NameInit {
String name;
public NameInit(String name)
{
this.name = name;
}
@Override
public String toString(){
return name;
}
}
PlaceAndAddInit
public class PlaceAndAddInit {
String place;
int value;
public PlaceAndAddInit(String place,int val) {
this.place = place;
this.value= val;
}
@Override
public String toString(){
return place+" "+value;
}
}
主类
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
HashMap h = new HashMap();
System.out.println("Limit: ");
int limit = scan.nextInt();
for(int i=0;i<limit;i++)
{
h.put(new NameInit(scan.next()), new PlaceAndAddInit(scan.next(),
scan.nextInt()));
}
System.out.println("Enter a key to search the value: ");//
NameInit key= new NameInit(scan.next());//asks for a input from the user to fetch the values
Set s = h.entrySet();
Iterator<NameInit> itr = s.iterator();
while(itr.hasNext())
{
Map.Entry<NameInit,PlaceAndAddInit> me = (Map.Entry) itr.next();
NameInit key1 =me.getKey();
if(key.equals(key1)){// this never happens with this code as key and key1 holds different hashcodes. So how do I achieve the equality.
System.out.println(me.getValue());
}
}
}
}
编辑:我尝试通过
equals方法获得相等性,我发现key1和key的哈希码不同。了解这背后的原因是我提出问题的目的。
【问题讨论】:
-
不清楚您的确切问题。你应该展示
NameInit的实现,至少对于equals()和hashCode()