There are two ways to sort list by using the Collections.sort method
The first is that the object in the list implements the comparable interface, as follows:
/**
* Sort the user according to order
*/
public class User implements comparable<user>{
private String name;
private Integer order;
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public Integer GetOrder () {
return order;
}
public void Setorder (Integer order) {
This.order = order;
}
public int CompareTo (User arg0) {
Return This.getorder (). CompareTo (Arg0.getorder ());
}
}
Test it:
public class test{
public static void Main (string[] args) {
User User1 = new user ();
User1.setname ("a");
User1.setorder (1);
User User2 = new user ();
User2.setname ("B");
User2.setorder (2);
list<user> list = new arraylist<user> ();
Add User2 and add user1 here
List.add (User2);
List.add (user1);
Collections.sort (list);
for (User u:list) {
System.out.println (U.getname ());
}
}
}
The output is as follows
A
B
The second method is implemented according to the Collections.sort overloaded method, for example:
/**
* Sort the user according to order
*/
public class User {//There is no need to implement comparable interface here
private String name;
private Integer order;
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public Integer GetOrder () {
return order;
}
public void Setorder (Integer order) {
This.order = order;
}
}
In the main class, you can write this:
public class test{
public static void Main (string[] args) {
User User1 = new user ();
User1.setname ("a");
User1.setorder (1);
User User2 = new user ();
User2.setname ("B");
User2.setorder (2);
list<user> list = new arraylist<user> ();
List.add (User2);
List.add (user1);
Collections.sort (list,new comparator<user> () {
public int Compare (user arg0, user arg1) {
Return Arg0.getorder (). CompareTo (Arg1.getorder ());
}
});
for (User u:list) {
System.out.println (U.getname ());
}
}
}
The output is as follows
A
B
The former code structure is simple, but can only be sorted according to fixed attributes, the latter flexible, can temporarily specify sort items, but the code is not concise
The use of merit.
Use of the Collections.sort () sort function in Java