Given a List of MyClass objects (and a custom Comparitor myComparitor if needed), what good options are there for checking if the List contains two “equal” objects?
Edit: if there are duplicates, return a reference to one or more of the duplicates.
Overriding MyClass.equals(MyClass) in this case is not an option.
My initial thought is to create a hash table of sorts, but I suspect that there’s a non-hack way to accomplish the same thing:
SortedSet mySet = new TreeSet(myComparitor);
mySet.addAll(myList);
// Find duplicates in a sorted set in O(N) time
P.S. Is there a good reference on Markdown?
If the element’s
equals(Object)method does not give you the semantic that you require, thenHashMaporHashSetare not options. Your choices are:TreeMapfor de-duping. This isO(NlogN).ArrayListor a copy, then iterate over looking for element i equals element i + 1. This isO(NlogN).equals(Object)andhashCode(), and de-dup using aHashSetof wrapped objects. This isO(N), but the constant of proportionality will be larger than a simpleHashSetdue to creation of wrapper objects.When de-duping with a
Setit is probably better to use a loop rather thanaddAll. This is necessary if you need to know what all of the duplicates are. If you don’t need to know that, then using a loop allows you to stop when you find the first duplicate. The only case whereaddAllis likely to perform better is when there are likely to be no duplicates.