java比较接口
1、Comparable接口
1.1、使用过程
- 类实现Comparable接口,制定泛型,重写compareTo(…)方法。
- 测试类中使用Collections或Arrays进行排序。
1.2、代码
public class UserInfo implements Comparable<UserInfo>{
private int id;
private String name;
private String address;
@Override
public int compareTo(UserInfo userInfo) {
return userInfo.id - this.id;
}
}
@Test
public void test01(){
UserInfo user1 = new UserInfo(1, "zhangsan", "wuhan");
UserInfo user2 = new UserInfo(5, "lisi", "macheng");
UserInfo user3 = new UserInfo(3, "wangwu", "beijing");
List<UserInfo> list = Arrays.asList(user1, user2, user3);
System.out.println("原始顺序:" + list);
Collections.sort(list);
System.out.println("排序后的顺序:" + list);
}
2、Comparator接口
2.1、使用过程
- 实体类不用做任何处理。
- 在排序是,创建匿名对象Comparator(…)对象处理逻辑。
2.2、代码
public class UserInfo{
private int id;
private String name;
private String address;
public UserInfo() {
}
public UserInfo(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@Test
public void test01(){
UserInfo user1 = new UserInfo(1, "zhangsan", "wuhan");
UserInfo user2 = new UserInfo(5, "lisi", "macheng");
UserInfo user3 = new UserInfo(3, "wangwu", "beijing");
List<UserInfo> list = Arrays.asList(user1, user2, user3);
System.out.println("原始顺序:" + list);
Collections.sort(list, new Comparator<UserInfo>() {
@Override
public int compare(UserInfo o1, UserInfo o2) {
return o1.getId() - o2.getId();
}
});
System.out.println("排序后的顺序:" + list);
}