Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two versions of <code>Collections.sort()</code> . </p> <p><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29" rel="nofollow">Collections.sort(List)</a> and <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,java.util.Comparator%29" rel="nofollow">Collections.sort(List,Comparator)</a> . One takes a <code>List</code>and another takes a <code>List</code> and an instance of <code>Comparator</code>. The single argument <code>sort()</code> will expect your class to have implemented <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html" rel="nofollow">Comparable</a> and overridden the <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html#compareTo%28T%29" rel="nofollow">compareTo()</a> method. The two argument <code>sort()</code> method expects an instance of <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html" rel="nofollow">Comparator</a>, wherein you have implemented the <code>Comparator</code> and overridden its <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare%28T,T%29" rel="nofollow">compare()</a> method.</p> <p>An object should implement <code>Comparable</code> if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.</p> <p>If, however, the sorting was an unusual use case of the class or there can be multiple sort orders then a <code>Comparator</code> is a better option.</p> <p><em>Also I have the Collections.sort(items) call right after I declare my ArrayList, is this okay?</em></p> <p>You will call <code>sort()</code> when you need to sort the <code>List</code>. Adding items after <code>sort()</code> won't automatically sort the <code>List</code> to accommodate the change in ordering of list items due to addition of new elements.</p> <p>Sample implementation:</p> <pre><code>public int compareTo (Item other) { return new Integer(this.getID()).compareTo(new Integer(other.getID())); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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