Comparable与Comparator
场景引入
需要对用户这个对象进行按照身高进行排序
@Getter
@Setter
public class User{
private Integer age; //年龄
private Integer height; //身高
private String username;
public User(Integer age, Integer height, String username) {
this.age = age;
this.height = height;
this.username = username;
}
}
Comparable
让User类实现Comparable接口并重写compareTo方法
@Getter
@Setter
public class User implements Comparable{
private Integer age; //年龄
private Integer height; //身高
private String username;
public User(Integer age, Integer height, String username) {
this.age = age;
this.height = height;
this.username = username;
}
@Override
public String toString() {
return "username:" + this.username + " age:" + this.age + " height:" + this.height;
}
@Override
public int compareTo(Object o) {
if (o instanceof User){
User u = (User)o;
return this.age.compareTo(u.getAge());
}
throw o == null ? new NullPointerException() : new ClassCastException();
}
public static void main(String[] args) {
TreeSet<User> set = new TreeSet();
set.add(new User(3, 172,"jiejie"));
set.add(new User(5, 180,"rose"));
set.add(new User(1, 163,"bard"));
set.add(new User(4, 155,"adc"));
set.forEach(user->{
System.out.println(user.toString());
});
}
}
执行main方法可以看到输出结果是按照age字段排序的,因为TreeSet具有排序功能,当然也可以用Collections.sort()等方法对集合进行排序,前提是这个集合所存储的对象具有排序功能
Comparator
现在要求对User的身高进行排序,按照刚刚Comparable的用法就只能去修改User类的代码,这样做是非常不推荐的,因此引入了Comparator比较器
public class UserHeightComparator implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
return o1.getHeight().compareTo(o2.getHeight());
}
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User(3, 172,"jiejie"));
users.add(new User(5, 180,"rose"));
users.add(new User(1, 163,"bard"));
users.add(new User(4, 155,"adc"));
Collections.sort(users,new UserHeightComparator());
users.forEach(user->{
System.out.println(user.toString());
});
}
}
执行main方法可以看到输出结果是按照Height字段排序的,Comparator可以根据我们不同的需求实现不同的排序方式,相比Comparable更加灵活。