Reputation: 2747
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<>();
temp.add("One");
temp.add("Two");
temp.add("Three");
Main.add(temp);// add this arraylist to the main array list
ArrayList<String> temp1 = new ArrayList<>();
temp1.add("One");
temp1.add("Two");
temp1.add("Three");
if(!Main.containsAll(temp1)) // check if temp1 is already in Main
{
Main.add(temp1);
}
}
}
When I print the contents of Main
, I obtain both temp
and temp1
. How can I fix this?
Upvotes: 1
Views: 6128
Reputation: 1308
What would you do if it was about ArrayList<Integer>
? There is such a method named contains()
. To check if your main list contains some object (another list) just invoke this function passing it as the parameter.
Upvotes: 0
Reputation: 137084
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:
List<String>
;"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)) {
Main.add(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.
Upvotes: 1
Reputation: 44965
You can use the method List#contains()
since contains
will check for instances of ArrayList
that are equal to the provided ArrayList
which will be the case here as temp.equals(temp1)
returns true
since the method equals
of an AbstractList
compares their content and here the content of those ArrayList
is equal.
if(!Main.contains(temp1)) // check if temp1 is already in Main
{
Main.add(temp1);
}
Upvotes: 2
Reputation: 41627
Since you want to avoid duplicate lists (and not check for the elements of the inner lists), just use Main.contains
instead of Main.containsAll
.
This will check whether the Main
list already contains a list with the elements you are about to add.
Upvotes: 1