Write a Java array ordering example, here to share for everyone to learn together
Copy Code code as follows:
Package com.yonyou.test;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;
Import java.util.List;
public class Test {
public static void Main (string[] args) {
Student ZLJ = new Student ("Dingxiaoyu", 21);
Student DXY = new Student ("Zhao Si", 22);
Student CJC = new Student ("John", 11);
Student LGC = new Student ("American", 19);
list<student> studentlist = new arraylist<student> ();
Studentlist.add (ZLJ);
Studentlist.add (DXY);
Studentlist.add (CJC);
Studentlist.add (LGC);
System.out.println ("Sorted according to Age:");
Collections.sort (Studentlist, New Sortbyage ());
for (Student student:studentlist) {
System.out.println (Student.getname () + "/" + student.getage ());
}
System.out.println ("=========");
System.out.println ("Sorted by name");
Collections.sort (Studentlist, New Sortbyname ());
for (Student student:studentlist) {
System.out.println (Student.getname () + "/" + student.getage ());
}
}
}
Class Sortbyage implements Comparator {
public int Compare (object O1, Object O2) {
Student S1 = (Student) O1;
Student s2 = (Student) O2;
if (S1.getage () > S2.getage ())
return 1;
else if (s1.getage () = = S2.getage ()) {
return 0;
}
return-1;
}
}
Class Sortbyname implements Comparator {
public int Compare (object O1, Object O2) {
Student S1 = (Student) O1;
Student s2 = (Student) O2;
if (S1.getname (). CompareTo (S2.getname ()) < 0)
return-1;
else if (S1.getname (). CompareTo (S2.getname ()) > 0) {
return 1;
}
return 0;
}
}
Class student{
private int age;
private String name;
public int getage () {
return age;
}
public void Setage (int age) {
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public Student (String Name,int age) {
This.age = age;
THIS.name = name;
}
}