Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

"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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!