Peng Zhanglong
Peng Zhanglong

Reputation: 15

check two objects are the same according to their property in JAVA

For example:

public class Fruit{
    private String color;
    private double weight;
    ...
    public boolean equals(Fruit a){
        return (this.getColor().equals(a.getColor()) && (this.getWeight()==a.getWeight()));
    }
}

public class Orange extends Fruit{
    public Orange(double weight) {
        super("orange", weight);
    }
}

public class NavalOrange extends Orange{
    public NavalOrange(double weight) {
        super(weight);
    }
}

Then I wrote a test about this to check two objects if they are same.

    Orange orange = new Orange(8);
    NavalOrange navalOrange = new NavalOrange(8);
    assertEquals(orange, navalOrange);

But it just keeps returning errors:

    junit.framework.AssertionFailedError: expected:<Orange@5305068a> but was:<NavalOrange@1f32e575>

Can anyone explain why this is happening? I think it may be something wrong at the toString method.

Upvotes: 1

Views: 153

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

There is no equals(Fruit) method in Object. You equals method should start with something like...

@Override
public boolean equals(Object a) {
    boolean equals = false;
    if (a instanceof Fruit) {
        ...
    }
    return equals;
}

Basically, all assertEquals is doing is using Object#equals. You can test this by adding the @Override annotation to your equals method and it will produce a compiler error, as `equals(Fruit) does not override any method from it's parent...

Also, if you override equals, you should override hashCode in order to maintain it's contract...

From the JavaDocs for Object#equals

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Upvotes: 2

Related Questions