Classes in Java implement the comparable interface for sorting

Source: Internet
Author: User
Tags comparable

Import Java.util.Arrays;

public class Sortapp {
public static void Main (string[] args) {
student[] Stus = new Student[3];
Stus[0] = new Student (11, 99);
STUS[1] = new Student (13, 92);
STUS[2] = new Student (13, 89);
Arrays.sort (Stus);
for (Student student:stus) {
System.out.println ("age=" + student.getage () + ";" + "score="
+ Student.getscore ());
}
}

Static Class Student implements Comparable<student> {
private int age;
private int score;

Public Student () {
}

Public Student (int age, int score) {
This.age = age;
This.score = score;
}

public int Getscore () {
return score;
}

public void SetScore (int score) {
This.score = score;
}

public int getage () {
return age;
}

public void Setage (int.) {
This.age = age;
}

public int compareTo (Student o) {
int result = this.age-o.age;//O indicates that the object to be compared will be sorted in descending order when the result is in ascending order as negative
if (Result! = 0) {
return result;
} else {
Return this.score-o.score;//If result=0 compares the second column
}
}

}
}

In the example above we sort the row as a key in Hadoop, because the default sort for Hadoop is only for key,value, and if you want to sort the value, we need to customize the collation to use KeyValue as key

Classes in Java implement the comparable interface for sorting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.