我的解决方案适用于不关心列表中的顺序的情况——换句话说:具有相同元素但顺序不同的列表将被认为具有相同的内容。
示例:["word1", "word2"]和["word2", "word1"]被认为内容相同。
我已经谈到了订购,我还需要说一些关于副本的事情。列表需要具有相同数量的元素才能被认为是相等的。
例如:["word1"]和["word1", "word1"]被认为不具有相同的内容。
我的解决方案:
public class ListUtil {
public static <T> boolean hasSameContents(List<T> firstList, List<T> secondList) {
if (firstList == secondList) { // same object
return true;
}
if (firstList != null && secondList != null) {
if (firstList.isEmpty() && secondList.isEmpty()) {
return true;
}
if (firstList.size() != secondList.size()) {
return false;
}
List<T> tmpSecondList = new ArrayList<>(secondList);
Object currFirstObject = null;
for (int i=1 ; i<=firstList.size() ; i++) {
currFirstObject = firstList.get(i-1);
boolean removed = tmpSecondList.remove(currFirstObject);
if (!removed) {
return false;
}
if (i != firstList.size()) { // Not the last element
if (tmpSecondList.isEmpty()) {
return false;
}
}
}
if (tmpSecondList.isEmpty()) {
return true;
}
}
return false;
}
}
我用Strings进行了测试,如下所示:
@Test
public void testHasSameContents() throws Exception {
// comparing with same list => no duplicate elements
Assert.isTrue(ListUtil.hasSameContents(List.of("one", "two", "three"), List.of("one", "two", "three")));
// comparing with same list => duplicate elements
Assert.isTrue(ListUtil.hasSameContents(List.of("one", "two", "three", "one"), List.of("one", "two", "three", "one")));
// compare with disordered list => no duplicate elements
Assert.isTrue(ListUtil.hasSameContents(List.of("one", "two", "three"), List.of("three", "two", "one")));
// compare with disordered list => duplicate elements
Assert.isTrue(ListUtil.hasSameContents(List.of("one", "two", "three", "one"), List.of("three", "two", "one", "one")));
// comparing with different list => same size, no duplicate elements
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "three"), List.of("four", "five", "six")));
// comparing with different list => same size, duplicate elements
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "two"), List.of("one", "two", "three")));
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "three"), List.of("one", "two", "two")));
// comparing with different list => different size, no duplicate elements
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "three", "four"), List.of("one", "two", "three")));
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "three"), List.of("one", "two", "three", "four")));
// comparing with different list => different sizes, duplicate elements
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "three", "one"), List.of("one", "two", "three")));
Assert.isFalse(ListUtil.hasSameContents(List.of("one", "two", "three"), List.of("one", "two", "three", "one")));
}