java arraylist equal,Java的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.

Example:

//These should be equal.

ArrayList listA = {"a", "b", "c"}

ArrayList listB = {"b", "c", "a"}

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?

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

解决方案

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 one, List 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(one);

two = new ArrayList(two);

Collections.sort(one);

Collections.sort(two);

return one.equals(two);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值