There are two ways to sort the list using the Collections.sort method
The first is that the objects in the list implement the Comparable interface, as follows:
[java] view plain copy
/**
* Sort Users according to order
*/
public class User implements Comparable< ;User>{
private String name; ;
}
public Integer getOrder( ) {
return order; , return this.getOrder().compareTo(arg0.getOrder() ; user1.setOrder "
//This Add user2 and then add user1
list.add(user2);
list.add(user1);
Collections.sort(list); (u.getName( ); #&*/BPublic class user {// here No need to implement the comparable interface
Private String name;
Private Integer Order; V PUBLIC VOID SETNAME (String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
}
Just write this in the main class (HastSet——>List——>sort to sort):
public class Test {
public static void main(String[] args) {
User user1 = new User();
user1.setName("a" ;
Set
list. addAll(Hset);
Collections.sort(list,new Comparator
public int compare(User arg0, User arg1) { .compareTo(arg1.getPrice()) ;
The output results are as follows:
a
b
The default is ascending order ,Will. return arg0.getOrder().compareTo(arg1.getOrder()); Change to:
return arg1.getOrder().compareTo(arg0.getOrder());
It will be in descending order.