2010-01-06 75 views
3

給定對象列表(所有相同類型),如何確保它僅包含某個屬性的每個值的一個元素,即使equals( )由於更多的屬性被檢查,可能會返回false這些元素?在代碼中:在列表中查找某些屬性具有相同值的對象

private void example() { 
    List<SomeType> listWithDuplicates = new ArrayList<SomeType>(); 

    /* 
    * create the "duplicate" objects. Note that both attributes passed to 
    * the constructor are used in equals(), though for the purpose of this 
    * question they are considered equal if the first argument was equal 
    */ 
    SomeType someObject1 = new SomeObject1("hello", "1"); 
    SomeType someObject2 = new SomeObject1("hello", "2"); 

    List<SomeType> listWithoutDuplicates = removeDuplicates(listWithDuplicates) 
    //listWithoutDuplicates should not contain someObject2 
} 

private List<SomeType> removeDuplicates(List<SomeType> listWithDuplicates) { 
    /* 
    * remove all but the first entry in the list where the first constructor- 
    * arg was the same 
    */ 
} 

回答

7

可以使用一個設置爲中介佔位符,找到重複的Bozho建議。這是一個示例removeDuplicates()的實現。

private List<SomeType> removeDuplicates(List<SomeType> listWithDuplicates) { 
    /* Set of all attributes seen so far */ 
    Set<AttributeType> attributes = new HashSet<AttributeType>(); 
    /* All confirmed duplicates go in here */ 
    List duplicates = new ArrayList<SomeType>(); 

    for(SomeType x : listWithDuplicates) { 
     if(attributes.contains(x.firstAttribute())) { 
      duplicates.add(x); 
     } 
     attributes.add(x.firstAttribute()); 
    } 
    /* Clean list without any dups */ 
    return listWithDuplicates.removeAll(duplicates); 
} 
0

如果equals()合適,我可以推薦一些「標準」集合類/方法。正因爲如此,我認爲你唯一的選擇將是要麼

  • 副本的每個元素到另一個列表先檢查所有前原列表重複元素之後;或

  • 從您的列表中刪除您在前一位置找到重複的任何元素。對於刪除列表,最好使用LinkedList,刪除並不昂貴。

在任一情況下,在檢查重複將是一個爲O​​(n^2)的操作,唉。


如果你要很多這種操作的,它可能是值得的包裹返回根據自己定義的標準的哈希碼另一個類中的列表元素。

1

也許是一個HashMap可以像這樣使用:

private List<SomeType> removeDuplicates(List<SomeType> listWithDuplicates) { 
    /* 
    * remove all but the first entry in the list where the first constructor- 
    * arg was the same 
    */ 
    Iterator<SomeType> iter = listWithDuplicates.iterator(); 
    Map<String, SomeType> map = new HashMap<String, SomeType>(); 
    while(iter.hasnext()){ 
     SomeType i = iter.next(); 
     if(!map.containsKey(i.getAttribute())){ 
      map.put(i.getAttribute(), i); 
     } 
    } 
    //At this point the map.values() is a collection of objects that are not duplicates. 



    } 
+0

可能會工作,但我會失去列表的順序。我必須檢查這是否是我的情況中的問題。 – 2010-01-06 11:58:33

相關問題