对于相同类型的两个用户定义对象,哈希码显示不同

Hashcodes are appearing different for two user defined objects of same type

我有一个程序可以搜索键以打印哈希图中的值。但是当我将输入 key 等同于 key1 时,我对键和值的输入是用户 defined.Now 的对象,为什么对象的哈希码 keykey1 在程序中出现不同,尽管 return 类型相同,即。 NameInit,其中 String str="abc"abc 的哈希码 return 相等?程序中如何判断keykey1是否相等?在类型转换为 Object class 后,我尝试了 Objects.equals(key,key1),但仍然没有 work.I 看到类似的问题,例如 [this question][1] 中讨论的关于哈希码相等性,但又如何像我的示例中那样使这些对象相等。请帮忙。
NameInit Class

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;
   }
}

主要Class

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());
            }
      }
    }
  }

Edit: I tried to obtain equality by equals method to which I discovered that hashcodes of key1 and key are different. Understanding the reason behind this is the purpose of my question.

Objects.equals是这样实现的:

return (a == b) || (a != null && a.equals(b));

你看,基本上就是调用aequals方法,不是hashcode 方法。无论hashcode如何实现,当a.equals(b) returns false时,Objects.equals returns false。它与hashcode方法无关。

因此,要解决此问题,只需覆盖 equals 方法即可。这是一个简单的实现:

@Override
public boolean equals(Object obj) {
    return this.hashcode() == obj.hashcode();
}

此外,如果您想在散列映射中查找某个键的值,请调用散列映射上的 get 方法,它会在 O(1) 时间内为您完成。不需要使用 O(n) 时间的这种低效方法。

您没有覆盖 hashCode(),因此使用默认值。在默认实现中,keykey1 将具有不同的 hashCode 值,即使您认为它们应该相等,它们也不会相等。因此,如果您希望能够比较这些对象,解决方案是重写 hashCodeequals 方法。

回答你的问题:

Edit: I tried to obtain equality by equals method to which I discovered that hashcodes of key1 and key are different. Understanding the reason behind this is the purpose of my question.

如果您不提供对 equalshashCode 的覆盖,它们将从 Object 继承。这是他们寻找 Object:

的方式
  public boolean equals(Object obj) {
        return (this == obj);
    }

因此,2 个对象只有在 == 时才相等,这意味着它们指向完全相同的内存位置。在您的示例中,情况并非如此。 hashCode 是原生的,所以不能给你看源代码。

这里有更多内容可供阅读:

Google search about hashCode and equals