Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an ArrayList contains a given object

Tags:

Assuming I have class like this:

class A {   int elementA;   int elementB } 

I also have an ArrayList like this: ArrayList<A> listObj.

How can I check if that list contains an object using only some of the properties of A? E.g. considering only elementA for finding if object newA{elementA} is already in the list?

For object A I have defined an equals method, where I consider only the elementA, however this is not enough.

like image 700
Saulius S Avatar asked Apr 29 '13 07:04

Saulius S


People also ask

How do you check if an ArrayList contains an array?

contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it​.

How do you check if an ArrayList contains another ArrayList?

The Java ArrayList containsAll() method checks whether the arraylist contains all the elements of the specified collection. The syntax of the containsAll() method is: arraylist. containsAll(Collection c);

Does ArrayList have Contains method?

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

How do you check if an ArrayList contains a substring 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

List#contains() method uses the equals() method to evaluate if two objects are the same. So, you need to override equals() in your Class A and also override the hashCode().

@Override public boolean equals(Object object) {     boolean isEqual= false;      if (object != null && object instanceof A)     {         isEqual = (this.elementA == ((A) object).elementA);     }      return isEqual; }  @Override public int hashCode() {     return this.elementA; } 
like image 186
AllTooSir Avatar answered Oct 28 '22 07:10

AllTooSir


You could adapt your equals to accomodate for your needs, but you could also use one of the powerful collection libraries that already exists, like commons-collections, Guava or lambdaj. They all have iteration and predicate constructs that allow you to "explore" your collections based on some predicate.

Example with Commons Collections:

boolean contains = CollectionUtils.exists(myArrayList, new Predicate<A>() {     public boolean evaluate(A theA) {         // Do the comparison     } }); 
like image 32
NilsH Avatar answered Oct 28 '22 07:10

NilsH