[英]Compare List<String[]>
我有兩個List<String[]>
(字符串數組列表),我想將內容相互匹配。 顯然==
沒有做到這一點,但.equals ()
似乎也沒有這樣做。 那么我應該如何檢查字符串數組列表的內容是否相同?
順便說一句,在上述兩種情況下,我都得到一個異常,消息為null
。
編輯:好的...出於某種原因只有x.equals(y)
工作,而不是y.equals(x)
。 奇...
也許最簡單的解決方案是使用兩個List<List<String>>
。 假設使用List
實現擴展AbstractList
,使用equals
將為您提供所需的行為。 從AbstractList.equals
的文檔:
將指定對象與此列表進行比較以獲得相等性。 當且僅當指定的對象也是列表時,返回
true
,兩個列表具有相同的大小,並且兩個列表中的所有對應元素對都相等 。 (如果(e1==null ? e2==null : e1.equals(e2))
則兩個元素e1
和e2
相等。)換句話說,如果兩個列表包含相同順序的相同元素,則它們被定義為相等。
您可以使用Arrays.asList
輕松地將String[]
包裝在擴展AbstractList
的瘦List<String>
實現中。
編輯:這是一個例子:
String[] array1 = {"1", "2", "3"};
String[] array2 = {"4", "7"};
String[] array3 = {"1", "2", "3"};
String[] array4 = {"4", "7"};
List<List<String>> lst1 = new ArrayList<>();
lst1.add(Arrays.asList(array1));
lst1.add(Arrays.asList(array2));
List<List<String>> lst2 = new ArrayList<>();
lst2.add(Arrays.asList(array3));
lst2.add(Arrays.asList(array4));
System.out.println(lst1.equals(lst2)); //prints true
通常你應該避免處理數組。 他們很丑,導致這些問題。 如果可能的話使用List<List<String>>
那么你可以正常使用.equals()
。
如果你堅持,你可以使用如下的自定義isequal實現。 關鍵是使用Arrays.equals()
public class DemoEquals {
List<String[]> listOne = (List<String[]>) Arrays.asList(new String[]{"one1", "one2"}, new String[]{"two1"});
List<String[]> listOneOne = (List<String[]>) Arrays.asList(new String[]{"one1", "one2"}, new String[]{"two1"});
List<String[]> listTwo = (List<String[]>) Arrays.asList(new String[]{"2one1", "2one2"}, new String[]{"2two1"});
private boolean isEqual(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;
}
@SuppressWarnings("unchecked")
private void isEqual() {
//prints true
System.out.println(isEqual(Collections.EMPTY_LIST, Collections.EMPTY_LIST));
//prints true
System.out.println(isEqual(listOne, listOne));
//prints true
System.out.println(isEqual(listOne, listOneOne));
//prints false
System.out.println(isEqual(listOne, listTwo));
//prints false
System.out.println(isEqual(listOne, Collections.EMPTY_LIST));
}
public static void main(String[] args) {
new DemoEquals().isEqual();
}
}
您可以使用INTERFACE Comparable。 實現所需的方法,您可以使用List1.compare(List2)函數。
只是.equals()
工作正常,但不知何故只在一個方向。
我打算在這個問題上接受第一個答案,但顯然那個人已經刪除了他的答案。
使用Jon Skeet關於如何將List轉換為String (使用Guava)的答案,另一種選擇是將2個列表轉換為2個字符串,然后使用equals
進行比較。 沒有循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.