如何判断两个列表是否相等

如何判断两个列表是否相等

本文介绍了Java ArrayList - 如何判断两个列表是否相等,顺序无关紧要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 ArrayList 类型的 Answer(自制类).

I have two ArrayLists of type Answer (self-made class).

我想比较这两个列表,看看它们是否包含相同的内容,但顺序无关紧要.

I'd like to compare the two lists to see if they contain the same contents, but without order mattering.

示例:

//These should be equal.
ArrayList<String> listA = {"a", "b", "c"}
ArrayList<String> listB = {"b", "c", "a"}

List.equals 声明如果两个列表包含相同的大小、内容和元素顺序,则它们是相等的.我想要同样的东西,但顺序无关紧要.

List.equals states that two lists are equal if they contain the same size, contents, and order of elements. I want the same thing, but without order mattering.

有没有简单的方法可以做到这一点?还是我需要做一个嵌套的 for 循环,然后手动检查两个列表的每个索引?

Is there a simple way to do this? Or will I need to do a nested for loop, and manually check each index of both lists?

注意:我不能将它们从 ArrayList 更改为另一种类型的列表,它们需要保持不变.

Note: I can't change them from ArrayList to another type of list, they need to remain that.

推荐答案

您可以使用 Collections.sort() 对两个列表进行排序,然后使用 equals 方法.稍微好一点的解决方案是在排序之前首先检查它们的长度是否相同,如果不是,则它们不相等,然后排序,然后使用相等.例如,如果您有两个字符串列表,它将类似于:

You could sort both lists using Collections.sort() and then use the equals method. A slighly better solution is to first check if they are the same length before ordering, if they are not, then they are not equal, then sort, then use equals. For example if you had two lists of Strings it would be something like:

public  boolean equalLists(List<String> one, List<String> two){
    if (one == null && two == null){
        return true;
    }

    if((one == null && two != null)
      || one != null && two == null
      || one.size() != two.size()){
        return false;
    }

    //to avoid messing the order of the lists we will use a copy
    //as noted in comments by A. R. S.
    one = new ArrayList<String>(one);
    two = new ArrayList<String>(two);

    Collections.sort(one);
    Collections.sort(two);
    return one.equals(two);
}

这篇关于Java ArrayList - 如何判断两个列表是否相等,顺序无关紧要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:09