Skip to content

The containsAll method return incorrect results when there are duplicate elements in the compared List in Java

The first List is [5,5,3,7,6] and named FirstList, another List is [5,5,5] and named SecList. When I invoke containsAll method like this FirstList.containsAll(SecList) to see if FirstList contains SecList. Obviously the answer is false, but the containsAll method return true, it’s a incorrect results.

The whole code is as follows:

    List<Integer> FirstList = new ArrayList<>();
    List<Integer> SecList = new ArrayList<>();

    for (int j = 0; j < 3; j++)
    {
        SecList.add(5);
    }

    FirstList.add(5);
    FirstList.add(5);
    FirstList.add(3);
    FirstList.add(7);
    FirstList.add(6);
    System.out.println("FirstList: " + FirstList);
    System.out.println("SecList: " + SecList);
    System.out.println("FirstList contains SecList?  " + FirstList.containsAll(SecList));

And the output is:

FirstList: [5,5,3,7,6]
SecList: [5,5,5]
FirstList contains SecList? true

It seems like this method can only produce correct results if the list does not contain duplicate elements. Is there any way to achieve this logic simply? Please forgive my poor English, and I really appreciate your help.

Answer

“Obviously the answer is false,”

The answer is true, and supposed to be true. For each element e in SecList, FirstList.contains(e) returns true. That’s how containsAll is supposed to work; there’s no bug here.

If you want that behavior, you will need to count elements in each collection, perhaps with a Map<E, Integer> or a Guava Multiset, and then compare the counts of each element.