比较字符串数组的数组列表 [英] Comparing array list of string array
本文介绍了比较字符串数组的数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个字符串数组的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());
如果对数组执行相等操作,它将检查引用是否相等.无论如何,我们可以使用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.
推荐答案
如果从 List< String []>
更改为 List<列表< String>>
.
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
这篇关于比较字符串数组的数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文