comparable
public class PersonTest{
public static void main(String[] args) {
Person[] people = new Person[]{
new Person(1,"11"),
new Person(2,"22"),
new Person(3,"33"),
};
java.util.Arrays.sort(people);
for(Person person : people ){
System.out.println(person.toString());
}
}
}
class Person implements Comparable<Person>{
private Integer age;
private String name;
public Person(Integer age, String name) {
super();
this.age = age;
this.name = name;
}
@Override
public int compareTo(Person o) {
if(o.age > this.age){
return -1;
}else{
return 1;
}
}
@Override
public String toString() {
return "Teacher [name=" + name + ", age=" + age + "]";
}
Comparator
public class ComparatorTest {
public static void main(String[] args) {
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if(o1.length() > o2.length()){
return -1;
}else{
return 1;
}
}
};
TreeSet<String> treeSet = new TreeSet<>(comparator);
treeSet.add("222555555");
treeSet.add("333");
treeSet.add("5555");
treeSet.add("666666");
System.out.println(treeSet.toString());
}
}
comparable 可比较的,在自定义类内部 重写compareTo 方法,相当于是类的内部有比较功能,需要修改原有类,且比较固定
comparator 比较器,不用修改原来的类,在外部实现一个比较规则,可以理解成一个外部比较器吧,比较灵活 可复用