'Comparison with the Method equal() [duplicate]
When i compare two instances in java of the same type class, with the same values of their Attributes, why i get false? I'm new with OOP and don't Understand some OOP logic.
public static void main(String[] args) {
Object o1= new Object(24,"Omar");
Object o2= new Object(24,"Omar");
System.out.println(o1.equals(o2));
}
Solution 1:[1]
The equals method returns true if and only if o1 and o2 refer to the same object. And if We want to compare with members variable, we need to override the equals method in our custom class like below:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomObjClass obj = (CustomObjClass) o;
return age == obj.age && Objects.equals(name, obj.name);
}
And then it will return true for the below code:
CustomObjClass o1= new CustomObjClass(24,"Omar");
CustomObjClass o2= new CustomObjClass(24,"Omar");
System.out.println(o1.equals(o2)); // return true
Solution 2:[2]
By default, the equals operator verifies if the two objects are the same one. So, for example, if we perform these operations:
Object o1= new Object(24,"Omar");
Object o2= o1
System.out.println(o1.equals(o2));
you would get true, as o2 is the same object as o1. In your case, you have two different objects (since you instantiate them with the "new") that have the same content. Therefore, the equal operator returns false. If you want it to return true, you have to override the equals operator and implement your own logic.
Solution 3:[3]
The default implementation of equals
method compares the reference of both the objects using ==
operator. You can find the details here. If you want to compare the value of your Class
override the equals
method.
Example:
public class TestClass {
private int age;
private String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TestClass)) return false;
TestClass testClass = (TestClass) o;
return getAge() == testClass.getAge() && Objects.equals(getName(), testClass.getName());
}
@Override
public int hashCode() {
return Objects.hash(getAge(), getName());
}
public TestClass(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rakib Hasan |
Solution 2 | molfo |
Solution 3 | Prog_G |