2013-09-27 49 views
0

我所提供的兩個陣列爪哇排序字符串數組,並返回不同項目

array 1 : a, b, c, d 
array 2 : a, b, c 

我已經使用了

ArrayList<String> combine = new ArrayList<String>() 

array 1所有元件和array 2

通過排序,我發現

a , a , b , b , c , c , d 

請問如何比較這兩個數組中的元素並返回不同的項目(例如d)?

回答

0

如果你想用數組來做,那麼你必須循環兩個數組並逐個比較值。如果你想用ArraysLists做到這一點,那麼你可以建立你的邏輯圍繞和remove()方法。

1

喜歡的東西

ArrayList<String> charsA = new ArrayList<>(); 
charsA.addAll(Arrays.asList("a", "a", "b", "c", "d")); 
ArrayList<String> charsB = new ArrayList<>(); 
charsB.addAll(Arrays.asList("a", "b", "c")); 

charsA.removeAll(charsB); 
System.out.println(charsA); 

打印

[d] 

顯然,使用不同的列表,如果你不希望任何兩個原始的受到影響。

removeAll(Collection)方法

從列表中移除所有包含在 指定集合中的元素。

0
List<String> list1 = new ArrayList<String>(); 
    list1.add("a"); 
    list1.add("b"); 
    list1.add("c"); 
    list1.add("d"); 

    List<String> list2 = new ArrayList<String>(); 
    list2.add("a"); 
    list2.add("b"); 
    list2.add("c"); 

    List<String> distinctList = new ArrayList<String>(); 

    for (String string : list1) { 
     if (!list2.contains(string)) { 
      distinctList.add(string); 
     } 
    }