简体   繁体   中英

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[]>();
megaData.add(data);
megaData.add(data2);

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

contains does not work in this case because the equals -method of an array only checks if the array-objects are the same, not if they have the same elements (cp. this post ). And contains uses equals .

My recommendation is to use only Lists s instead of arrays. List s have an equals -method that compares the lists' elements. The first lines of the code have to be changed for this:

List<Integer> data  = Arrays.asList(1,2);
List<Integer> data2 = Arrays.asList(3,4);
List<Integer> dataCheck = Arrays.asList(1,2);
List<List<Integer>> megaData= new ArrayList<List<Integer>>();

Arrays.asList is an easy way to create a list with fixed elements. List s are usually declared with only the interface List and not the implementing class like ArrayList . This makes it easy to use another List -implementation at a later point of time.

That could be:

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

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;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM