the first is that the objects in the list implement the comparable interface , as follows:
/**
* Sort 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 ());
}
}
</user>
Test:
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>
();
Here add user2 add user1
list.add (user2);
List.add (user1);
Collections.sort (list);
for (User u:list) {
System.out.println (U.getname ());
}
}} </user>
</user>
The output is as follows
A
B
The second approach is based on the Collections.sort overload method , for example:
/**
* Sort User According to order * * The public
class User {//here does not need to implement the comparable interface
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;
}
}
This can be written in the main class:
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 ());
}
}} </user>
</user>
</user>
The output is as follows
A
B
The former code is simple, but can only be sorted according to the fixed attributes, the latter is flexible, you can temporarily specify the sort items, but the code is not concise
Multi-field occasions:
Collections.sort (list,new Comparator
<user>
() {public
int compare (user arg0, user arg1) {
// first comparison professional
int i = Arg0.getorder (). CompareTo (Arg1.getorder ()); If the profession is the same, perform a second comparison if
(i==0) {
// second comparison
int j=arg0.getxxx (). CompareTo (Arg1.getxxx ()); if the same length of schooling is returned by age order if
(j==0) {return
ARG0.GETCCC (). CompareTo (ARG1.GETCCC ());
}
return j;
}
return i;
}
});
</user>
The above is a small series to introduce you to the Collections.sort method in the Java collection how to sort list (two methods), I hope to help.