Re: Best way to check if all elements in a List are unique



On 03/01/2010 06:36 PM, Tom Anderson wrote:
if (cur.equals(prev)) return false;

What if there are null entries in the list?

This snippet also, of course, assumes that T is a comparable object (I believe Collections.sort fails if there's no comparator and T can't be cast to Comparable).

The HashSets also assume that you're checking equality via .equals (as opposed to using ==), and that .hashCode() is correctly implemented, i.e., consistent with equals.

--
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
.



Relevant Pages

  • Re: Farge zu TreeSet
    ... comparator is provided) must be consistent with equals if it is to ... Set interface is defined in terms of the equals operation, ... der von Malte zitierten throws-Clause von Comparable#compareTo (bzw. ...
    (de.comp.lang.java)
  • Re: Alternative to TreeSet?
    ... TreeSet doesn't do the job. ... "Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be ... consistent with equals if it is to correctly implement the Set interface. ... Suppose a sorted set (or sorted map) with an explicit ...
    (comp.lang.java.programmer)
  • Re: problem with Sets
    ... adds the specified element e to this set if the ... "Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. ...
    (comp.lang.java.programmer)
  • Re: case insensitive sort
    ... like this in the Comparator ... " The natural ordering for a class C is said to be consistent with equals ... This is so because sorted sets (and sorted maps) ...
    (comp.lang.java.programmer)
  • Re: How to check variables for uniqueness ?
    ... public boolean areEqual ... Problems caused by comparators not consitent with an object's equals method could be avoided by supplying an Equalizer that is consistent with the comparator, as well as it obviating the need you perceive to wrap the String class. ...
    (comp.lang.java.programmer)