Home > Java > javaTutorial > body text

Collection (object) sorting

巴扎黑
Release: 2016-12-10 09:22:00
Original
1687 people have browsed it

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 Hset = new HashSet();              Hset.add(user2); ;User>();
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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template