Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a ArrayList's contains() method evaluate objects?

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?

like image 342
Mantas Vidutis Avatar asked Apr 15 '10 03:04

Mantas Vidutis


People also ask

How does contains method work in Java ArrayList?

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.

How do you check if an ArrayList contains an object?

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.

Does ArrayList contain contains method?

Java ArrayList contains()The contains() method checks if the specified element is present in the arraylist.

How list contains method in Java?

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.


2 Answers

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.

like image 120
Binary Nerd Avatar answered Sep 23 '22 02:09

Binary Nerd


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;     } } 
like image 28
ChristopheCVB Avatar answered Sep 22 '22 02:09

ChristopheCVB