我有一个列表列表,我想向其中添加一个列表,不要重复。另一方面,我想检查该列表是否已包含在主列表中。我写过这样的东西
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);
}
}
}
当我打印 Main
的内容时,我同时获得了 temp
和 temp1
。我该如何解决这个问题?
最佳答案
您可以使用方法List#contains()
因为 contains
将检查与提供的 ArrayList
相同的 ArrayList
实例,这里就是 temp.equals( temp1)
返回 true
,因为 AbstractList
的方法 equals
将它们的内容与此处那些 ArrayList< 的内容进行比较
是相等的。
if(!Main.contains(temp1)) // check if temp1 is already in Main
{
Main.add(temp1);
}
关于java - 检查一个 ArrayList 是否包含另一个 ArrayList 作为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754725/