2010-07-09 69 views
2
public void removeDuplicates (ArrayList<ArrayList<String>> strings) { 

    Set<ArrayList<String>> s = new LinkedHashSet<ArrayList<String>>(strings); 
    strings = new ArrayList<ArrayList<String>>(s); 
} 

我想刪除在ArrayList<ArrayList<String>>重複的行,我想使用LinkedHashSet和自身之間比較ArrayList,如果是相同的不插入。我知道我需要Comparator,但我不知道如何實施ArrayListArrayList比較ArrayList刪除重複的線<ArrayList中<String>>

THX

+1

一些示例將有助於闡明您的意圖。 – polygenelubricants 2010-07-09 11:54:43

+0

查看「在C#中刪除列表中的重複項」 http://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in-c – Gage 2010-07-09 12:03:30

+0

@Gage:原理當然是一樣的,但是這個問題被標記爲'[java]'。 – 2010-07-09 15:53:08

回答

4

您可以嘗試使用集合< List> - 如果您實現自己的List或擴展ArrayList os,那麼「equals()」按照您的期望行事。

所以,當你添加一個arrayList時,它會自動與其餘的進行比較。

不確定當你首先添加arrayLists然後用元素填充它們會發生什麼。

你的情況如何?


你說你要使用LinkedHashSet - 好吧,這是一樣的我的初步建議。 (你不需要比較) 你可以擴展ArrayList和使其 「的equals()」 方法符合你的願望:

  • 相同數量的元素
  • 相同的元素
  • 等...
0

你將不得不做蠻力比較和每一個ArrayList中對所有其他數組列表進行比較。

開始索引爲0,並比較其反對指引元件的1-N一旦你找到一個

Assumeing的ArrayList myDatastructure以下僞代碼:

for (int i =0; i < myDatastructure.count() ; i++){ 

    for (int j = i+1 ; i< mydatastructure.count() ; j++){ 
     compare(myDatastructure.get(i),myDataStructure.get(j)); 

    } 
} 

的比較方法,你會想要寫一個爲循環遍歷所有元素,比較兩個arrayLists中每個索引處的項目,如果它們不是相同的長度,則不需要比較它們就可以將其短路。

你可能想要標記你想在一個單獨的arraylist中刪除的索引,並在一個單獨的循環中刪除它們,否則你會搞砸你的索引。

實現應該相當簡單,所以這只是一個練習。

0

說列表中包含

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 

你期望的設置爲C什麼ontain?兩個要素?一個元素?

你能告訴你如何比較ArrayLists嗎?

如果是一個對一個比較 - 「他們是平等的,如果它們包含在相同順序相同元素」,然後

sets = new HashSet<ArrayList<String>>(lists); 

應該足夠了。

如果你想有更復雜的比較規則,那麼你需要重寫Leni Kirilov上面所說的equals方法。但是列表越大,您的性能開銷就越高。

+0

thx所有的答案。你提供的列表是不一樣的,所以可以添加。我需要一對一的比較,但你的代碼與main相同,不起作用。所有重複都不會被刪除。你說覆蓋equals(),你有任何例子如何?如果我重寫equals()我也需要重寫hashCode。 – senzacionale 2010-07-09 12:30:33

1

你沒有提到訂單是否重要。

如果在內部列表中的項目順序並不重要,這應該工作: -

List<List<String>> list = new ArrayList<List<String>>(); 
list.add(Arrays.asList(new String[] { 
     "a", 
     "b", 
     "c" 
})); 
list.add(Arrays.asList(new String[] { 
     "b", 
     "a", 
     "c" 
})); 
list.add(Arrays.asList(new String[] { 
     "a", 
     "b", 
     "c", 
     "d" 
})); 

// use set to remove duplicates 
Set<Set<String>> set = new HashSet<Set<String>>(); 
for (List<String> innerList : list) { 
    set.add(new HashSet<String>(innerList)); 
} 

// convert back to list 
List<List<String>> noDupList = new ArrayList<List<String>>(); 
for (Set<String> innerSet : set) { 
    noDupList.add(new ArrayList<String>(innerSet)); 
} 

// print out for debugging 
for (List<String> l : noDupList) { 
    System.out.println(l); 
} 
0

與@Leni以上同意,只是覆蓋的ArrayList的等於方法和LinkedHashSet實現應該自動過濾重複項。

來自Java文檔:一個不包含重複元素的集合。更正式地,集合不包含e1和e2這樣的元素對,使得e1.equals(e2)和至多一個空元素。正如其名稱所暗示的那樣,此接口模擬數學集抽象

+0

它永遠不會「只是覆蓋等於」,顯然不是當你立即將它用於哈希集合。需要重寫hashCode。 – 2010-07-09 19:09:12

相關問題