user3841581 user3841581 - 3 months ago 14
Java Question

Checking if an ArrayList contains another ArrayList as element

I have a list of lists and I would like to add a list to it, without duplicate. In other to do that, I would like to check if that list is already contained in the main list. I have written something like this

import java.util.ArrayList;
public class Test{
public static void main(String [] args)
ArrayList<ArrayList<String>> Main = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
Main.add(temp);// add this arraylist to the main array list
ArrayList<String> temp1 = new ArrayList<>();


if(!Main.containsAll(temp1)) // check if temp1 is already in Main

When I print the contents of
, I obtain both
. How can I fix this?


The issue here is that you're getting confused with the use of containsAll and the list of lists.

containsAll is a method that checks whether this collection contains all of the elements of the given collection. In this case:

  • This collection has 1 element, which is a List<String>;
  • The given collection has 3 elements, which are "One, "Two" and "Three".

And clearly, this collection, which only contains a List<String> (which is ["First, "Two", "Three"]), does not contain the 3 elements; it only contains a list of those three elements.

So what you really want here isn't containsAll, but contains, i.e. you want to check whether your list contains another list (and not its elements).

The following works:

if (!Main.contains(temp1)) {

and will result in Main being [[One, Two, Three]], added just once.

The side question is: why does it work? Well now, the question is: does my List<List<String>>, which is [[One, Two, Three]], contains this List<String>, which is [One, Two, Three]? Since two lists are equal when they have the same size and all of their elements are equal, it does contain it.