I have an ArrayList<MyObject>
that may (or may not) contain duplicates of MyObject
I need to remove from the List. How can I do this in a way that I don't have to check duplication twice as I would do if I were to iterate the list in two for-loops and cross checking every item with every other item.
I just need to check every item once, so comparing A:B
is enough - I don't want to compare B:A
again, as I already did that.
Furthermore; can I just remove duplicates from the list while looping? Or will that somehow break the list and my loop?
Edit: Okay, I forgot an important part looking through the first answers: A duplicate of MyObject
is not just meant in the Java way meaning Object.equals(Object), but I need to be able to compare objects using my own algorithm, as the equality of MyObject
s is calculated using an algorithm that checks the Object's fields in a special way that I need to implement!
Furthermore, I can't just override euqals
in MyObject
as there are several, different Algorithms that implement different strategies for checking the equality of two MyObject
s - e.g. there is a simple HashComparer
and a more complex EuclidDistanceComparer
, both being AbstractComparers
implementing different algorithms for the public abstract boolean isEqual(MyObject obj1, MyObject obj2);