Implementation of Java ArrayList automatic sorting algorithm __ algorithm

Source: Internet
Author: User

The one that was written a few days ago is wrong, here will be the correct update ...

By implementing the comparator interface and rewriting the Compare function, the custom collation implements the ordering of objects in ArrayList.

Student class Definition:

Automatically generate set and get methods by right-clicking-"source-"

package;

Import Java.util.Comparator;
Import java.io.*;
public class Student implements serializable,comparator<student> {
String ID;
String name;
int score;
Public String getId () {
return ID;
}
public void SetId (String id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int Getscore () {
return score;
}
public void SetScore (int result) {
This.score = result;
}
public void SetAll (String id,string name,int score) {
This.id=id;
This.name=name;
This.score=score;
}
Public String toString () {
Return (this.id+ "" +this.name+ "" +this.score);
}
@Override
public int Compare (Student stu_1, Student stu_2) {
if (Stu_1.score>stu_2.score)
return-1;
Else
return 1;
}

}

Application:

arraylist<student> Stuarray = new arraylist<student> ();

Collections.sort (Stuarray, New Student ());

This enables the 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.