这Equals_to_operator
是一个类,具有参数化的构造函数public Equals_to_operator(int dd, int mm, int yy)
。e
和f
是两个对象,它们使用相同的参数调用参数化的构造函数。我已经覆盖了hashCode
并使两个对象的hashCode相同。即使使哈希码相同(对象的内存位置相同),它也会给出Output:not equals
我想通过使哈希码相同来执行相同的操作,这是我哪里出错了?
public class Equals_to_operator {
private int dd,mm,yy;
public Equals_to_operator(int dd, int mm, int yy) {
this.dd = dd;
this.mm = mm;
this.yy = yy;
}
@Override
public String toString() {
return "Equals_to_operator [dd=" + dd + ", mm=" + mm + ", yy=" + yy + "]";
}
public int hashCode() {
return 1;
}
public static void main(String[] args) {
Equals_to_operator e=new Equals_to_operator(7, 1, 2016);
System.out.println(e+"\n"+e.hashCode());
Equals_to_operator f=new Equals_to_operator(7, 1, 2016);
System.out.println(f+"\n"+f.hashCode());
if (e==f)
System.out.println("equals");
else
System.out.println("not equals");
}
即使使哈希码相同(对象的内存位置相同),它也会给出Output:not equals
具有相同的哈希码并不意味着对象相等。
memory location of object same
……这不是哈希码的作用。你从哪里得到的?
如果(e == f)
这意味着,条件将IFF既真e
且f
都指向同一个对象。
根据您的equals
方法,e
和指向的两个对象f
都是相等的,但是==
要检查引用的相等性而不是内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句