1.Comparator位于包java.util下,而Comparable位于包java.lang下。
2.Comparable接口将比较代码嵌入需要进行比较的类的自身代码中,而Comparator接口在一个独立的类中实现比较。
3.Comparable接口强制进行自然排序,而Comparator接口不强制进行自然排序,可以指定排序顺序。
一,定义一个java类对象
public class User {
private String userId;
private String userName;
private String userAge;
private String userAlias;
private String sex;
}
二,使用comparator重写compare方法,进行排序(升序降序都可以),使用方法如下:
再次强调:Comparable接口将比较代码嵌入需要进行比较的类的自身代码中,而Comparator接口在一个独立的类中实现比较。
package com.hg.demo;
import com.hg.demo.test.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>();
User user1 = new User("3","a341r","33","陈三","男");
User user2 = new User("7","eff3","31","阿猫","男");
User user3 = new User("5","q44t","5","阿狗","男");
User user4 = new User("9","a2f4","83","张三","男");
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
Collections.sort(list, new Comparator() {
@Override
public int compare(User o1, User o2) {
/**
* 一:字符串比较
* 升序:o1-o2
* 降序:o2-o1
* 使用默认的时区和locale ,指定为中国locale
*/
/* Collator collator = Collator.getInstance(Locale.CHINA);
int value = collator.compare(o1.getUserName(),o2.getUserName());
if(value>0){
return 1;
}else if(value<0){
return -1;
}else{
return 0;
}*/
/**
* 二:数字比较
* 升序:o1-o2
* 降序:o2-o1
*/
return Integer.valueOf(o2.getUserId())-Integer.valueOf(o1.getUserId());
}
});
for (User u : list) {
System.out.println(u.getUserId()+"--"+u.getUserName()+"--"+u.getUserAge()+"--"+u.getUserAlias());
}
}
}
输出结果:
类必须实现Comparable接口,必须重写compareTo方法
public class User implements Comparable{
private String userId;
private String userName;
private String userAge;
private String userAlias;
private String sex;
@Override
public int compareTo(Object o) {
User u = (User)o;
/**
* 比较属性必须是数字类型
* 升序:this - u
* 降序:u - this
*
*/
return Integer.valueOf(u.getUserId())- Integer.valueOf(this.getUserId());
}
// get set 省略
}
测试输出
package com.hg.demo;
import com.hg.demo.test.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
List list = new ArrayList<>();
User user1 = new User("3", "a341r", "33", "陈三", "男");
User user2 = new User("7", "eff3", "31", "阿猫", "男");
User user3 = new User("5", "q44t", "5", "阿狗", "男");
User user4 = new User("9", "a2f4", "83", "张三", "男");
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
Collections.sort(list);
for (User u : list) {
System.out.println(u.getUserId() + "--" + u.getUserName() + "--" + u.getUserAge() + "--" + u.getUserAlias());
}
}
}
结果: