HumparDumpar HumparDumpar - 11 months ago 35
Java Question

I have an arrayList where each element is an array of integers of length . How do i use .contains method here?

I know it is a bit confusing, but i basically wanna check if an arrayList of integer Arrays contains an array or not? I have added a code for more sense.

I was trying the following code. But .contains method doesnt seem to work when checking for an array. An alternative method will be very helpful.

int [] data = {1,2};
int [] data2= {3,4};
int [] dataCheck = {1,2};
ArrayList<int[]> megaData= new ArrayList<int[]>();


if (megaData.contains(dataCheck)){

System.out.println("A copy has been found");


System.out.println("No copy found");

Answer Source

That could be:

boolean contains = false;
for (int[] element : megaData) { // iterating over the list
    if (Arrays.equals(element, dataCheck)) {
        contains = true;

if (contains) {
    System.out.println("A copy has been found");
} else {
    System.out.println("No copy found");

Alternatively, you could write a method for this:

public boolean containsArray(ArrayList<int[]> listOfArrays, int[] array) {
    for (int[] element : listOfArrays) {
        if (Arrays.equals(element, array)) {
            return true;
    return false;