简体   繁体   English

Java中的重写equals方法,但得到逻辑错误/意外结果

[英]overriding equals method in java but getting logical errors/unexpected results

In this program i was trying to compare the field value of two reference variable value by overriding equals method---- Here is the code---- 在此程序中,我试图通过覆盖等于方法比较两个参考变量值的字段值----这是代码----

public class D {
int i,j;

 D(int i,int j)
 {
     this.i=i;
     this.j=j;
 }
 public boolean equals(Object f)
 {
    boolean s= (this.i==((D)f).i);
    boolean n= (this.j==((D)f).j);
    return s==n;
 }
}

public class run02 {
 public static void main(String[] args){
 D d=new D(4,5);
 D d1=new D(6,7);
 D d2=new D(8,10);
 System.out.println(d.equals(d1));//comparing reference variable value
 System.out.println(d1.equals(d2));//comparing reference variable value
 System.out.println(d);//printing reference variable memory address
 System.out.println((d==d1));//comparing reference variable memory address
 }
}

Output-true//comparing reference variable value
       true//comparing reference variable value
       firstProg.e@g3h742//memory address
       false//comparing reference variable memory address

When i was trying to create a method public boolean equals(int i, intj) without giving return value then java throws compilation error. 当我试图创建一个方法public boolean equals(int i,intj)而不给出返回值时,java抛出编译错误。

The problem lies in this line: 问题出在这一行:

return s==n;

Here, this will return true if both s and n are false . 在这里,如果sn均为false ,则返回true

You should use s && n to return true only if both s and n are true . 你应该用s && n返回true只有当两个sntrue

When i was trying to create a method public boolean equals(int i, intj) without giving return value then java throws compilation error. 当我试图创建一个方法public boolean equals(int i,intj)而不给出返回值时,java抛出编译错误。

Yes it will give you a compilation error because you are trying to cheat compiler, as in the method signature you are promising the compiler that at the end you will give it a boolean but in the end you are giving it anything. 是的,它会给您带来编译错误,因为您正试图欺骗编译器,因为在方法签名中,您向编译器承诺,最后将给它一个布尔值,但最后却给它任何东西。 So, that's why the compiler is complaining. 因此,这就是编译器抱怨的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM