I am trying to compare two arraylist for its content, but even it contains the same element, it returns false everytime.
ArrayList<Apple> expected = new ArrayList<Apple>();
expected.add(new Apple(155,"green"));
expected.add(new Apple(160,"brown"));
System.out.println(expected);
ArrayList<Apple> actual = new ArrayList<>();
actual.add(new Apple(155,"green"));
actual.add(new Apple(160,"brown"));
System.out.println(actual);
boolean compare = actual.equals(expected);
System.out.println(compare);
output
[Apple{color='green', weight=155}, Apple{color='brown', weight=160}]
false
CodePudding user response:
By default equals uses references (place in memory). You use 2 different objects ( expected.add(new Apple(155,"green")); and actual.add(new Apple(155,"green")); ) so they are stored in different places in memory. You have to write your own function for object Apple that compares these objects by values and returns true or false.
CodePudding user response:
If you use equals() method of Object class (Default Implementation), it checks for references, not values. You have to override it in your class. String class has it's own overridden implementation of equals() method from object class. It compares values. In case of other primitives, == operator works for the same.
@Override
public boolean equals(Object obj) {
if(obj instanceof Apple) { // Instance checking must
Apple apple = (Apple) obj; // Type conversion must
if(apple.getColor().equals(this.getColor())
&& apple.getWeight()==this.getWeight()){
return true;
}
}
return false;
}
