查找两个不同列表是否包含完全相同元素的简单方法? [英] Simple way to find if two different lists contain exactly the same elements?

查看:34
本文介绍了查找两个不同列表是否包含完全相同元素的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在标准 Java 库中,查找两个 List 是否包含完全相同的元素的最简单方法是什么?

What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?

两个Lists是否是同一个实例无关紧要,Lists的类型参数是否不同也无关紧要.

It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.

例如

List list1
List<String> list2; 
// ... construct etc

list1.add("A");
list2.add("A"); 
// the function, given these two lists, should return true

我知道可能有什么东西盯着我看:-)

There's probably something staring me in the face I know :-)

为了澄清,我正在寻找完全相同的元素和元素数量,按顺序.

To clarify, I was looking for the EXACT same elements and number of elements, in order.

推荐答案

如果你在意顺序,那么就用equals方法:

If you care about order, then just use the equals method:

list1.equals(list2)

来自 javadoc:

From the javadoc:

将指定的对象与这份平等清单.返回真当且仅当指定的对象是也是一个列表,两个列表都有相同的大小,以及所有对应的对两个列表中的元素相等.(两个元素 e1 和 e2 相等,如果(e1==null ? e2==null :e1.equals(e2)).) 换句话说,两个如果列表被定义为相等包含相同的元素命令.这个定义确保equals 方法正常工作跨越不同的实现列表界面.

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

如果您想独立于顺序进行检查,您可以将所有元素复制到 Sets 并在结果 Sets 上使用 equals:

If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:

public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}

这种方法的一个限制是它不仅忽略了顺序,而且忽略了重复元素的频率.例如,如果 list1 是 ["A", "B", "A"] 并且 list2 是 ["A", "B", "B"]Set 方法会认为它们是相等的.

A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if list1 was ["A", "B", "A"] and list2 was ["A", "B", "B"] the Set approach would consider them to be equal.

如果您需要对订单不敏感但对重复的频率敏感,您可以:

If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:

这篇关于查找两个不同列表是否包含完全相同元素的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆