Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda