![](/img/trans.png)
[英]Check if an ArrayList contains the same element as another ArrayList
[英]Checking if an ArrayList contains another ArrayList as element
我有一个列表列表,我想向其中添加一个列表,不要重复。 在其他方面,我想检查该列表是否已包含在主列表中。 我写过这样的东西
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);
}
由于您想避免重复列表(而不是检查内部列表的元素),只需使用Main.contains
而不是Main.containsAll
。
这将检查Main
列表是否已经包含一个包含您将要添加的元素的列表。
这里的问题是您对containsAll
和列表列表的使用感到困惑。
containsAll
是一种检查此集合是否包含给定集合的所有元素的方法。 在这种情况下:
List<String>
;"One
, "Two"
和"Three"
。 很明显,这个只包含List<String>
(即["First, "Two", "Three"]
)的集合不包含这 3 个元素;它只包含这三个元素的列表。
所以你真正想要的不是containsAll
,而是contains
,即你想检查你的列表是否包含另一个列表(而不是它的元素)。
以下工作:
if (!Main.contains(temp1)) {
Main.add(temp1);
}
并将导致Main
为[[One, Two, Three]]
,只添加一次。
附带的问题是:为什么它有效? 现在,问题是:我的List<List<String>>
是否包含[[One, Two, Three]]
,包含这个List<String>
,即[One, Two, Three]
? 由于两个列表在大小相同并且它们的所有元素都相等时是相等的,因此它确实包含它。
如果是关于ArrayList<Integer>
你会怎么做? 有一个名为contains()
的方法。 要检查您的主列表是否包含某个对象(另一个列表),只需调用此函数将其作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.