I was doing some equality testing, and when comparing two objects, being a clone of the other, I noticed that equals
returns false
, even the objects being identical. The return should not be true
since they are cloned objects? Why does this happen?
Object Class:
public class SomeObject implements Cloneable{
private int identifier;
private String someDescription;
public SomeObject() {
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
public SomeObject(int identifier, String someDescription) {
super();
this.identifier = identifier;
this.someDescription = someDescription;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public String getSomeDescription() {
return someDescription;
}
public void setSomeDescription(String someDescription) {
this.someDescription = someDescription;
}
@Override
public String toString() {
return "[" + this.identifier + " - " + this.someDescription + "]";
}
}
The test I did was:
SomeObject obj1 = new SomeObject(1, "Lorem ipsum");
SomeObject obj2 = (SomeObject) obj1.clone();
System.out.println("Object 1: " + obj1);
System.out.println("Object 2: " + obj2);
System.out.println(obj1.equals(obj2));
Results in
Object 1: [1 - Lorem ipsum] Object 2: [1 - Lorem ipsum] São iguais? false
Test reproduced in ideone .