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?
Main.add(new ArrayList<String>(temp));. Directly adding temp would set a reference to the temp variable (object) and that's not something you'd want.