Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conventions used in Java documentation

Why does the Oracle Java API documentation for the add() method for TreeSet and HashSet state that:

an element e is added only if there is no e2 in the set where (e==null ? e2==null : e.equals(e2))

However, TreeSet uses compareTo(), while HashSet uses hashCode() to determine equality. Both ignore the value of equals(). I am concerned that the documentation is inaccurate, or is it my understanding of convention or the algorithm that is faulty?

like image 625
user3038094 Avatar asked Oct 21 '22 20:10

user3038094


2 Answers

You are correct that the TreeSet documentation is incorrect.

You are incorrect about HashSet, as it does use equals(). hashCode() is not used for equality testing, only for fast searching.

like image 138
jtahlborn Avatar answered Oct 23 '22 21:10

jtahlborn


TreeSet explains this in its doc:

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. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

For HashSet, it's an implicit expectation of the doc that the objects in the Set are correctly implemented; if hashCode() isn't correctly implemented, then it is not HashSet violating its spec but the objects being passed to it.

like image 42
Louis Wasserman Avatar answered Oct 23 '22 23:10

Louis Wasserman