Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>TreeSet</code> forms a binary tree keeping elements according to natural (or not) orders, so in order to search quickly one specific element is the collection, <code>TreeSet</code> uses <code>Comparable</code> or <code>Comparator</code> instead of <code>equals()</code>.</p> <p>As <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html" rel="nofollow">TreeSet</a> JavaDoc precises: </p> <blockquote> <p>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.</p> </blockquote> <p>We can find a similarity with the HashCode/Equals contract:</p> <p><em>If <code>equals()</code> returns <code>true</code>, <code>hashcode()</code> <strong>has to</strong> return true too in order to be found during search.</em></p> <p>Likewise with <code>TreeSet</code>:</p> <p><em>If <code>contains()</code> (using <code>Comparator</code> or <code>Comparable</code>) returns <code>true</code>, <code>equals()</code> <strong>has to</strong> return <code>true</code> too in order to be <strong>consistent</strong> with <code>equals()</code>.</em></p> <p><strong>THEREFORE:</strong> Fields used within <code>TreeSet.equals()</code> method have to be exactly the same (no more, no less) than within your <code>Comparator</code> implementation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload