0

Now I have 3object

user[0] = new user("a", "a");
user[1] = new user("b", "b");
user[2] = new user("c", "c");

there have many variable in the object such as: age, name, email

then the program is running.....

user[0].setAge(6);
user[1].setAge(5);
user[2].setAge(7);

how can I get the young to old user name?

the exception return: b,a,c

hksfho
  • 114
  • 1
  • 10

1 Answers1

1

You can either make User Comparable and have it's natural ordering by age:

public class User implements Comparable<User> {
    // snipped...

    @Override
    public int compareTo (User other) {
        return Integer.compare(age, other.age);
    }
}

Or explicitly specify a Comparator when you're sorting:

Collections.sort(users, new Comparator<User>() {
    @Override
    public int compare(User a, User b) {
        return Integer.compare(a.getAge(), b.getAge());
    }
});
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Mureinik
  • 297,002
  • 52
  • 306
  • 350