給定對象列表(所有相同類型),如何確保它僅包含某個屬性的每個值的一個元素,即使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