给定对象列表(所有相同类型),如何确保它仅包含某个属性的每个值的一个元素,即使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
*/
}
可能会工作,但我会失去列表的顺序。我必须检查这是否是我的情况中的问题。 – 2010-01-06 11:58:33