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
?
ArrayList contains() MethodThis method takes one object as its parameter. It checks if this object is in the ArrayList or not.It returns one boolean value. If the ArrayList contains at least one element, then it returns true. Else it returns false.
To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.
Java ArrayList contains()The contains() method checks if the specified element is present in the arraylist.
ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
ArrayList implements
the List Interface.
If you look at the Javadoc for List
at the contains
method you will see that it uses the equals()
method to evaluate if two objects are the same.
I think that right implementations should be
public class Thing { public int value; public Thing (int x) { this.value = x; } @Override public boolean equals(Object object) { boolean sameSame = false; if (object != null && object instanceof Thing) { sameSame = this.value == ((Thing) object).value; } return sameSame; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With