Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ul> <li><p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#higher%28E%29" rel="nofollow"><code>set.higher(T)</code></a>: function returns the least element in this set strictly greater than the given element, or <code>null</code> if there is no such element.</p></li> <li><p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#descendingSet%28%29" rel="nofollow"><code>set.descendingSet()</code></a>: returns a reverse order <code>view</code> of the elements contained in this <code>set</code>. </p></li> </ul> <p><strong>What really happens ?</strong></p> <p><code>TreeSet</code> inherently uses <code>TreeMap</code> to implements its functionality. The call to <code>descendingSet()</code> eventually call the <code>descendingMap()</code> function on the <code>TreeMap</code> instance, as is evident from the following source code: </p> <pre><code>public NavigableSet&lt;E&gt; descendingSet() { return new TreeSet&lt;&gt;(m.descendingMap()); } </code></pre> <p>Every <code>TreeMap</code> generally maintains two view: </p> <ul> <li><em>normal sorted view</em>: uses general comparator to order its element </li> <li><em>descendant Map view</em>: uses comparator which imposes reverse ordering of the ascend-ordering comparator. It uses <code>Collections.reverseOrder(m.comparator())</code> to return this descend-ordering comparator. </li> </ul> <p>I am calling these <code>view</code> because <code>TreeMap</code> doesn't actually create another descendent Map with it's <em>entries(key, value)</em>, rather it maintains two comparator, imposing opposite ordering to each other. The descendant view gets created first time when <code>descendantMap()</code> is called. Any subsequent call to this function will return the same descendent Map view.</p> <p><strong>Note:</strong> <code>set.descendingSet().descendingSet()</code> returns a view of <code>set</code> essentially equivalent to <code>set</code>. Because the resulted comparator from first call got reversed <em>again</em> by the second call of <code>descendingSet()</code>(which is actually executing <code>map.descendingMap()</code> inside).</p> <p><strong>Continuing with your Example:</strong> </p> <pre><code>System.out.printf("%n Higher than 40 : %s", set.higher(40)); // prints 45 set = set.descendingSet(); // create a reverse ordering //comparator as described above System.out.printf("%n Higher than 40 : %s", set.higher(40)); // prints 34 set = set.descendingSet(); // again trying to get descending set! System.out.printf("%n Higher than 40 : %s", set.higher(40)) // prints 45 </code></pre>
 

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