JAVA对象主要通过实现Comparable接口的compareTo方法来定义对象排序列,代码如下:
package com.study;
public class User implements Comparable<User>{
private String userName;
public User(){};
public User(User user){
this.userName = user.userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public int compareTo(User o) {
return this.userName.compareTo(o.getUserName());
}
}
调用Collections.sort(List<T>)方法来实现对象升序排序
package com.study;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testObjextPX {
public static void main(String[] args){
User user1 = new User();
user1.setUserName("zhangsan");
User user2 = new User();
user2.setUserName("lisi");
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
Collections.sort(list);
for(User u:list){
System.out.println(u.getUserName());
}
}
}
输出结果:
lisi
zhangsan
可调用:
Collections.sort(List<T>,Collections.reverseOrder())进行降序操作
Collections.reverse(List<T>)进行逆序操作