Ways to sort classes in Java

Source: Internet
Author: User

The comparer interface in Java comparable is used for sorting array objects, and to use this feature, you must have the class inherit from the comparable interface, overriding the CompareTo (object obj) method.

Import java.util.*;

Class Person implements comparable{
private String name;
private int age;
private float score;
Public person (String Name,int age,float score) {
This.name=name;
This.age=age;
This.score=score;
}
Public String toString () {
Return "Name:" +this.name+ ", Age:" +this.age+ ", Score:" +this.score;
}
public int compareTo (Object obj) {
Person P = (person) obj;
if (P.score>this.score) {
return 1;
}
else if (P.score<this.score) {
return-1;
}
else{
if (p.age>this.age) {
return 1;
}
else if (p.age<this.age) {
return-1;
}
else{
return 0;
}
}
}
}
public class oodemo35{
public static void Main (String []args) {
Person p[] = new PERSON[5];
P[0] = new Person ("Zhang San", 23,96);
P[1] = new Person ("Zhang 32", 24,96);
P[2] = new Person ("Zhang 33", 21,94);
P[3] = new Person ("Zhang 34", 22,98);
P[4] = new Person ("Zhang 35", 20,89);

Arrays.sort (P);
for (int x=0;x<p.length;x++) {
System.out.println (P[x]);
}
}
}

Output Result:

Name: Zhang 34, age: 22, Score: 98.0
Name: Zhang 32, Age: 24, Score: 96.0
Name: Zhang San, age: 23, Score: 96.0
Name: Zhang 33, age: 21, Score: 94.0
Name: Zhang 35, age: 20, Score: 89.0

How to sort classes in Java (GO)

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.