Tag: 哈希码

如何实现hashCode和equals方法

我应该如何在Java中为以下类实现hashCode()和equals() ? class Emp { int empid ; // unique across all the departments String name; String dept_name ; String code ; // unique for the department }

哈希码和等于

equals和hashCode方法必须一致,这意味着当两个对象根据equals方法相等时,它们的hashCode方法应返回相同的哈希值。 如果我们不重写hashCode()方法,Java将返回唯一的哈希码。 class HashValue { int x; public boolean equals(Object oo) { // if(oo instanceof Hashvalue) uncommenting ths gives error.dunno why? // 😐 HashValue hh = (HashValue) oo; if (this.x == hh.x) return true; else return false; } HashValue() { x = 11; } } class Hashing { public static void main(String args[]) { HashValue […]

有效Java hashCode()实现中的位移

我想知道是否有人可以详细解释什么 (int)(l ^ (l >>> 32)); 在下面的hashcode实现中(由eclipse生成,但与Effective Java相同): private int i; private char c; private boolean b; private short s; private long l; private double d; private float f; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + i; result = prime * result […]

在HashMap中加倍

我正在考虑使用Double作为HashMap的关键,但我知道浮点数比较是不安全的,这让我思考。 Double类上的equals方法也不安全吗? 如果那样则意味着hashCode方法可能也是错误的。 这意味着使用Double作为HashMap的关键将导致不可预测的行为。 任何人都可以在这里证实我的任何猜测吗?

当我覆盖equals()方法时,为什么要覆盖hashCode()?

好吧,我从许多地方和消息来源得知,每当我覆盖equals()方法时,我也需要覆盖hashCode()方法。 但请考虑以下代码 package test; public class MyCustomObject { int intVal1; int intVal2; public MyCustomObject(int val1, int val2){ intVal1 = val1; intVal2 = val2; } public boolean equals(Object obj){ return (((MyCustomObject)obj).intVal1 == this.intVal1) && (((MyCustomObject)obj).intVal2 == this.intVal2); } public static void main(String a[]){ MyCustomObject m1 = new MyCustomObject(3,5); MyCustomObject m2 = new MyCustomObject(3,5); MyCustomObject m3 = […]

如何确保hashCode()与equals()一致?

当重写java.lang.Object的equals()函数时,javadocs建议, 通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等的对象必须具有相等的哈希代码。 hashCode()方法必须为每个对象返回一个唯一的整数 (这在基于内存位置比较对象时很容易,只需返回对象的唯一整数地址) 应该如何覆盖hashCode()方法,以便它仅基于该对象的特性为每个对象返回一个唯一的整数 ? public class People{ public String name; public int age; public int hashCode(){ // How to get a unique integer based on name and age? } } /*******************************/ public class App{ public static void main( String args[] ){ People mike = new People(); People melissa = new People(); mike.name = […]