Say I create one object and add it to my ArrayList
. If I then create another object with exactly the same constructor input, will the contains()
method evaluate the two objects to be the same? Assume the constructor doesn't do anything funny with the input, and the variables stored in both objects are identical.
ArrayList<Thing> basket = new ArrayList<Thing>();
Thing thing = new Thing(100);
basket.add(thing);
Thing another = new Thing(100);
basket.contains(another); // true or false?
class Thing {
public int value;
public Thing (int x) {
value = x;
}
equals (Thing x) {
if (x.value == value) return true;
return false;
}
}
Is this how the class
should be implemented to have contains()
return true
?
Best Answer
ArrayList
implements
the List Interface.If you look at the Javadoc for
List
at thecontains
method you will see that it uses theequals()
method to evaluate if two objects are the same.