Java比较无序的ArrayLists

标签 java arraylist unordered

有人知道判断两个数组列表是否包含相同值的有效方法吗?

代码:

ArrayList<String> dummy1= new ArrayList<String>();
list1.put("foo");
list1.put("baa");

ArrayList<String> dummy2= new ArrayList<String>();
list1.put("baa");
list1.put("foo");

dummy1 == dummy2

挑战在于数组列表的值顺序不同..

(foo, baa) == (foo, baa) // per definition :)

我需要得到这个

(foo, baa) == (baa, foo) // true

那么您的方法是什么?

最佳答案

先排序吧。

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);
}

老实说,您应该检查一下您的数据结构决策。这看起来更像是一个集合问题。先排序再比较的时间复杂度为 O(nlog n),而 HashSet 比较的时间复杂度仅为 O(n)。

关于Java比较无序的ArrayLists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20054737/

相关文章:

java - 检查 ArrayList 是否包含某个字符串,同时不区分大小写

如果将大小大于 1995 的数组传递给数组 a,Python 程序将停止工作

c++ - shrink_to_fit() 用于无序容器?

java - 有没有比 ArrayList 更适合这种场景的集合?

javascript - 如何将json对象插入到无序列表中

error-handling - Xtext : Customizing Error msg by unordered groups

java - 在 HQL 中的两个表之间使用 LEFT JOIN

java - 时隙系统中的垃圾收集

java - 使用preferIPv6Addresses时出现SocketException

java - 使用 IntelliJ 调试 GIT