0

Is there a way to check if an ArrayList contains an array of objects? For example I have an arrayList

ArrayList<Integer[]> myList = new ArrayList<Integer[]>();
mylist.add(new Integer[]{5,5});
mylist.add(new Integer[]{1,1});

I would like to check if it contains a specific Integer array. Like:

Integer[] myArray = new Integer[]{5,5};

if I use the myList.containts(myArray); it should return true, but it checks if the Integer object is containted, not the array Values.

Is there a way to check the values?

1
  • You'll have to do it on your own, values cannot be assessed like this. Commented Jul 12, 2014 at 13:03

1 Answer 1

7

java.util.Arrays contains several array-related utility methods, including Arrays.deepEquals(Object[] a1, Object[] a2). You can scan the list looking for any element that is equal to new Integer[]{5,5} according to that test:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
  public static void main(String[] args) {
    ArrayList<Integer[]> myList = new ArrayList<Integer[]>();
    myList.add(new Integer[] { 5, 5 });
    myList.add(new Integer[] { 1, 1 });
    System.out.println(deepContains(myList, new Integer[] { 5, 5 }));
    System.out.println(deepContains(myList, new Integer[] { 5, 3 }));
  }

  public static boolean deepContains(List<Integer[]> list, Integer[] probe) {
    for (Integer[] element : list) {
      if (Arrays.deepEquals(element, probe)) {
        return true;
      }
    }
    return false;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.