Comparable和 Comparator区别
Comparable:内部比较器
- 写在排序对象内部
- 实现Comparable接口
- 该接口只有一个compareTo方法
@Date
@ToString
public class Peson implements Comparable<Peson> {
private String name;
private Integer age;
@Override
public int compareTo(Peson peson) {
return this.getAge()-peson.getAge();
}
}
// 测试类
public class Test {
public static void main(String[] args) {
five();
}
public static void five(){
Peson[] pesons = new Peson[]{
new Peson("hhh",11241),
new Peson("hhh",312),
new Peson("hhh",5123),
new Peson("hhh",13212)
};
Arrays.sort(pesons);
System.out.println(Arrays.toString(pesons));
}
}
打印结果
[Peson{name=‘hhh’, age=312}, Peson{name=‘hhh’, age=5123}, Peson{name=‘hhh’, age=11241}, Peson{name=‘hhh’, age=13212}]
Comparator:外部比较器
- 在需要排序的时候在定义具体的排序规则(说白了就是现调现用)
- 在java中,如果要对集合对象或数组对象进行排序,需要实现Comparator接口。
@Date
@ToString
public class User {
private String name;
private Integer age;
}
// 测试类
public class Test {
public static void main(String[] args) {
Two();
}
public static void Two(){
List<User> list = new ArrayList<>();
User user1 = new User("小米",123);
User user2 = new User("小米",312);
User user3 = new User("小米",1);
User user4 = new User("小米",5);
Collections.addAll(list,user1,user2,user3,user4);
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.age-o2.age;
}
});
System.out.println(list);
}
}
打印结果
[User{name=‘小米’, age=‘1’}, User{name=‘小米’, age=‘5’}, User{name=‘小米’, age=‘123’}, User{name=‘小米’, age=‘312’}]
set排序
Set是个无序、不可重复的集合接口;有三个实现类: HashSet、TreeSet、LinkedHashSet;
其中TreeSet 元素是可以进行排序的;
一
public class TestTwo {
public static void main(String[] args) {
six();
}
public static void six(){
String a ="3,2,1,4,3,5,9,8,7,123,321,12";
String[] split = a.split(",");
Set<Integer> set = new HashSet<Integer>();
for (String str: split
) {
set.add(Integer.valueOf(str));
}
TreeSet<Integer> tSet = new TreeSet<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
tSet.addAll(set);
System.out.println(tSet);
}
}