ArrayList里面的对象实现 Comparable接口
// User.java 待排序的对象 ,实现了Comparable接口
public class User implements Comparable{
private String name;
private String pass;
private int age;
public String getName() {
return name;
}
public String getPass() {
return pass;
}
public void setName(String name) {
this.name = name;
}
public void setPass(String pass) {
this.pass = pass;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) {
User user = (User) o;
if (this.age > user.age){
return 1;
}else if (this.age < user.age){
return -1;
}else {
return this.name.compareTo(user.name);
}
}
}
// Demo.java 测试程序
public class Demo {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
int lastAge = -1;
for (int i = 0; i < 20; i++) {
User user = new User();
if (lastAge==-1){
int number = (int) (Math.random() * 100);
user.setAge(number);
lastAge = number;
}else {
user.setAge(lastAge);
lastAge = -1;
}
int n = 20 - i;
user.setName(n + "haha");
user.setPass(n + "");
users.add(user);
}
Collections.sort(users);
for (int i = 0; i < 20; i++) {
User user = users.get(i);
System.out.println(user.getName() + " " + user.getAge() + " " + user.getPass());
}
}
}
调用排序,只需要Collections.sort(users); 即可。运行结果:略