I have got class TestObject with two variables: int A, and int B. I have got a list of TestObjects, and I would like to remove from the list duplicates (Objects that contains the same A and the same B variable.)
- Object 1 (A=1,B=1)
- Object 2 (A=2,B=2)
- Object 3 (A=1,B=1)
In this case I would like to remove from the list Object 1 OR 3, it doesn't matter which.
Objects are different instances, so standard:
LinkedHashSet<TestObject> hs = new LinkedHashSet<TestObject>();
hs.addAll(TestObjectList);
new.clear();
new.addAll(hs);
This will not work. Is there any easy way to achieve my goal? I tried using iterator inside iterator:
ListIterator<TestObject> iter = TestObjectList.listIterator();
while(iter.hasNext()){
TestObject to = iter.next();
ListIterator<TestObject> iter2 = TestObjectList.listIterator();
while(iter2.hasNext()){
TestObject to2 = iter2.next();
if(to.A==to2.A && to.B == to2.B){
iter.remove();
}
}
}
But I get following exception:
Exception in thread "main" java.util.ConcurrentModificationException' on line "TestObject to2 = iter2.next();
Unfortunnately, I have no other idea in what way I may achieve this goal. Maybe there is an easier way?