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"
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With