Java的ArrayList的 - 我怎么能知道,如果两个列表是相等的,为了不无所谓? [英] Java ArrayList - how can I tell if two lists are equal, order not mattering?

查看:195
本文介绍了Java的ArrayList的 - 我怎么能知道,如果两个列表是相等的,为了不无所谓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我型答(自制类)两个的ArrayList。

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.

有没有一种简单的方法来做到这一点?或将我需要做一个嵌套循环,手动检查两个列表中的每个索引?

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.

推荐答案

您既可以使用名单 Col​​lections.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的 - 我怎么能知道,如果两个列表是相等的,为了不无所谓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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