6
I was doing some equality tests, and when comparing two objects, being a clone of the other, I noticed that the equals
returns false
, even though the objects are 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 took 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.
Great question I also had this question ;D
– gato
Your method
clone()
will never launchCloneNotSupportedException
because theclone()
ofObject
only if the spear!(this instanceof Cloneable)
. So you can put onetry-catch
around thesuper.clone()
, capture theCloneNotSupportedException
and ignore it or encapsulate it in aAssertionError
. With that you get rid of having thethrows CloneNotSupportedException
in its method and avoids making the other methods have to capture this exception.– Victor Stafusa
Another ingrate downvote, serious people are voting a lot for empathy and dislike instead of voting for the quality of the post, votes are looking like facebook.
– Guilherme Nascimento