Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can encapsulate the related fields into a class, e.g. a <code>StudentRecord</code> can encapsulate the fields <code>name</code> and <code>score</code>.</p> <p>Now, you sort a collection of these objects based on the second field, <code>score</code>. When it comes time to print the sorted result, you iterate through the collection and print the first field, <code>name</code>.</p> <p>To illustrate:</p> <pre><code>public class StudentRecord implements Comparable&lt;StudentRecord&gt; { private String name; private int score; public StudentRecord(String name, int score) { this.name = name; this.score = score; } @Override public int compareTo(StudentRecord other) { if (score == other.score) return 0; else if (score &lt; other.score) return -1; else return 1; } @Override public String toString() { return name; } public static void main(String[] args) { StudentRecord stu1 = new StudentRecord("Matt", 50); StudentRecord stu2 = new StudentRecord("John", 90); if (stu1.compareTo(stu2) == 0) { System.out.println(stu1.toString() + " has the same score with " + stu2.toString()); } else if (stu1.compareTo(stu2) &lt; 0) { System.out.println(stu1.toString() + " has a lower score than " + stu2.toString()); } else { System.out.println(stu1.toString() + " has a higher score than " + stu2.toString()); } // output: // Matt has a lower score than John } } </code></pre> <p>In many sorting algorithms, implementing the <code>Comparable</code> interface gives the algorithm enough information to sort a collection of such objects implementing said interface.</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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