程序员:Comparable接口和Comparator接口的比较( 二 )


Comparable接口强制进行自然排序,而Comparator接口不强制进行自然排序,可以指定排序顺序 。
实例:
public class UserInfo {
private int id;
private String name;
private int age;
public UserInfo(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "UserInfo[id=" + id + " name=" + name + " age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
 
public class InterTest {
public static void main(String[] args) {
List<UserInfo> userInfoList = new ArrayList<>();
userInfoList.add(new UserInfo(0, "大强", 12));
userInfoList.add(new UserInfo(1, "大黄", 18));
userInfoList.add(new UserInfo(2, "大黑", 16));
userInfoList.add(new UserInfo(0, "大白", 52));
userInfoList.add(new UserInfo(0, "红红", 8));
userInfoList.add(new UserInfo(0, "翠花", 16));
userInfoList.add(new UserInfo(0, "芹菜", 36));
System.out.println("排序前");
for (UserInfo userInfo : userInfoList) {
System.out.println(userInfo);
}
Collections.sort(userInfoList, new Comparator<UserInfo>() {
@Override
public int compare(UserInfo o1, UserInfo o2) {
return o1.getAge() > o2.getAge() ? 1 : (o1.getAge() == o2.getAge() ? 0 : -1);
}
});
System.out.println("排序后");
for (UserInfo userInfo : userInfoList) {
System.out.println(userInfo);
}
}
}
 
输出:
排序前
UserInfo[id=0 name=大强 age=12]
UserInfo[id=1 name=大黄 age=18]
UserInfo[id=2 name=大黑 age=16]
UserInfo[id=0 name=大白 age=52]
UserInfo[id=0 name=红红 age=8]
UserInfo[id=0 name=翠花 age=16]
UserInfo[id=0 name=芹菜 age=36]
排序后
UserInfo[id=0 name=大红 age=8]
UserInfo[id=0 name=大强 age=12]
UserInfo[id=2 name=大黑 age=16]
UserInfo[id=0 name=翠花 age=16]
UserInfo[id=1 name=大黄 age=18]
UserInfo[id=0 name=芹菜 age=36]
UserInfo[id=0 name=大白 age=52]
 
 




推荐阅读