0

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.

saurav
  • 3,424
  • 1
  • 22
  • 33
Shantanu Nandan
  • 1,438
  • 8
  • 30
  • 56
  • 3
    Whenever you override `equals` or `hashcode` method, [you should always override the other](http://stackoverflow.com/q/27581/1679863). – Rohit Jain Aug 12 '13 at 19:42
  • 1
    Give meaningful names to classes / variables, it would help both SO community in helping you, and yourself in understanding your code some days later. – moonwave99 Aug 12 '13 at 19:45

2 Answers2

12

The problem lies in this line:

return s==n;

Here, this will return true if both s and n are false.

You should use s && n to return true only if both s and n are true.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

When i was trying to create a method public boolean equals(int i, intj) without giving return value then java throws compilation error.

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.

Justinw
  • 631
  • 10
  • 18
saurav
  • 3,424
  • 1
  • 22
  • 33