Question:
There is a list consisting of arrays ArrayList<int[]> list1;
. And the second list is smaller ArrayList<int[]> list2;
.
But to compare if list1
contains list2
, for some reason this entry doesn't work:
list1.containsAll(list2);
always returns false
, even if you know in advance that list1
contains list2
.
What could be the problem?
Answer:
The principle of the collectionA.containsAll(collectionB)
method is as follows:
For each element of collection B, a check is made to see if it belongs to collection A.
This check is as follows:
One element B is taken and compared in a loop with each element of collection A.
Moreover, the comparison is carried out using the equals
method. Your collections contain arrays. Arrays do not override the equals
method. Thus, the equals
method from the Object class will be used, which will give true
only if both references refer to the same array in memory.
It's like comparing arrays using the ==
operator. In your case, in different collections you have different arrays that will never give true
when calling the equals
method