加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java比较无序的ArrayLists

发布时间:2020-12-15 03:15:09 所属栏目:Java 来源:网络整理
导读:任何人都知道一种有效的方法来决定两个arraylists是否包含相同的值? 码: ArrayListString dummy1= new ArrayListString();list1.put("foo");list1.put("baa");ArrayListString dummy2= new ArrayListString();list1.put("baa");list1.put("foo");dummy1 ==
任何人都知道一种有效的方法来决定两个arraylists是否包含相同的值?

码:

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

挑战在于,arraylists没有相同的价值秩序.

(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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读