现在我有3个对象
user[0] = new user("a", "a");
user[1] = new user("b", "b");
user[2] = new user("c", "c");
对象中有许多变量,例如: 年龄,姓名,电子邮件
然后程序正在运行.....
user[0].setAge(6);
user[1].setAge(5);
user[2].setAge(7);
如何获得年轻人的旧用户名?
我想回复: B,A,C
这是班级
public class user{
int age;
String name;
String email;
public user(String name, String email){
this.name = name;
this.email = email;
}
public int getAge(){
return x;
}
public void setAge(int age){
this.age = age;
}
}
答案 0 :(得分:0)
您可以User
Comparable
按年龄自然排序:
public class User implements Comparable<User> {
// snipped...
@Override
public int compareTo (User other) {
return Integer.compare(age, other.age);
}
}
或者在您进行排序时明确指定Comparator
:
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User a, User b) {
return Integer.compare(a.getAge(), b.getAge());
}
});