Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java (Equals Method)

Tags:

java

class Employee{

  private String name;

  private int rollno;

public Employee(String name,int rollno)
{

  this.name=name;

  this.rollno=rollno;

}

}

public class CT2{

public static void main(String[]args){

Employee emp1 = new Employee("Raghu",35);

Employee emp2 = new Employee("Raghu",35);

Employee emp3 = new Employee("Raghu",35);

if(emp2.equals(emp3))

 System.out.println("They are equal");

else

 System.out.println("They are not equal");

}

}

What is wrong with the above code?? Ideally it should print "They are equal" but i am getting output as "They are not equal"

like image 714
Aryan Ragavan Avatar asked Dec 22 '15 08:12

Aryan Ragavan


1 Answers

You need to implement equals method in your class.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Adding below method will work for you.

@Override
public boolean equals(Object o) {

    // If the object is compared with itself then return true  
    if (o == this) {
        return true;
    }

    /* Check if o is an instance of Complex or not
      "null instanceof [type]" also returns false */
    if (!(o instanceof Employee)) {
        return false;
    }

    // typecast o to Complex so that we can compare data members 
    Employee c = (Employee) o;

    // Compare the data members and return accordingly 
    return (rollno == c.rollno && Objects.equals(name, c.name))
}
like image 115
codingenious Avatar answered Sep 28 '22 06:09

codingenious