- <div class="blockcode"><blockquote>//为什么运行后结果一直是按照添加顺序走,而没有按照我的比较器顺序排??
- import java.util.ArrayList;
- import java.util.Iterator;
- public class UserTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ArrayList<User> list = new ArrayList<>();
- list.add(new User("张三", 12));
- list.add(new User("李四", 14));
- list.add(new User("王五", 13));
-
- Iterator<User> iterator = list.iterator();
- while (iterator.hasNext()) {
- User user = (User) iterator.next();
- System.err.println(user);
- }
- System.out.println(list);
- }
- }
复制代码
public class User implements Comparable<Object> {
private String name;
private int age;
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
public User() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Object o) {
User user = (User)o;
int result = this.age - user.getAge();
if (result == 0) {
result = this.name.compareTo(user.getName());
}
return result;
}
}
|
|