2010-01-06 74 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

相关问题