且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java ArrayList - 如何判断两个列表是否相等,顺序无关紧要?

更新时间:2022-11-17 18:58:09

您可以使用 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);
}