本文介绍了比较字符串数组的数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个字符串数组的ArrayList.
I want to compare two ArrayList of string arrays.
List<String[]> list1 = new ArrayList<String[]>;
List<String[]> list2 = new ArrayList<String[]>;
list1.equals(list2);
这将返回 false,因为 ArrayList 中的 equals 方法将对元素执行 equals.
This will return false because equals method in ArrayList will do equals on the element.
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
如果你在数组上做 equals,它会检查引用是否相等.无论如何我们可以使用 list1.equals(list2) 而不是检查数组列表中的每个元素.
If you do equals on array, it will check reference equality. Is there anyway we can use list1.equals(list2) instead of checking each element in array list.
推荐答案
如果将 ,则可以使用 list1.equals(list2)列表>List
更改为 List
.
public static void main(String[] args) throws Exception {
List<List<String>> list1 = new ArrayList() {{
add(new ArrayList(Arrays.asList("a", "b", "c")));
add(new ArrayList(Arrays.asList("d", "e", "f")));
add(new ArrayList(Arrays.asList("g", "h", "i")));
}};
List<List<String>> list2 = new ArrayList() {{
add(new ArrayList(Arrays.asList("a", "b", "c")));
add(new ArrayList(Arrays.asList("d", "e", "f")));
add(new ArrayList(Arrays.asList("g", "h", "i")));
}};
System.out.println(list1);
System.out.println(list2);
System.out.println(list1.equals(list2));
}
结果:
[[a, b, c], [d, e, f], [g, h, i]]
[[a, b, c], [d, e, f], [g, h, i]]
true
否则,您可能正在寻找以下内容:
Otherwise, you're probably looking something along the lines of:
public static void main(String[] args) throws Exception {
List<String[]> list1 = new ArrayList() {{
add(new String[] {"a", "b", "c"});
add(new String[] {"d", "e", "f"});
add(new String[] {"g", "h", "i"});
}};
List<String[]> list2 = new ArrayList() {{
add(new String[] {"a", "b", "c"});
add(new String[] {"d", "e", "f"});
add(new String[] {"g", "h", "i"});
}};
System.out.println(listsEqual(list1, list2));
}
public static boolean listsEqual(List<String[]> list1, List<String[]> list2) {
if (list1.size() != list2.size()) {
return false;
}
for (int i = 0; i < list1.size(); i++) {
if (!Arrays.equals(list1.get(i), list2.get(i))){
return false;
}
}
return true;
}
结果:
true
这篇关于比较字符串数组的数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!