# comparable和comparator区别

1.comparable和comparator都是用来实现treeset等根据类的自然排序进行排序的集合容器中元素之间的比较，比较算法都是由比较器自己规定

1.comparable是让集合元素自身具备比较性，让元素实现comparable接口，覆盖comparaeTo(T o)方法

2.comparator是让集合具备比较性，在集合初始化时就有了比较放松，定义一个类，实现compare（T o1,T o2）方法

``````import java.util.Iterator;
import java.util.TreeSet;

/**
* @author WangShuang
*
*/
public class Demo {
public static void main(String[] args) {
Person p0 = new Person("张三",3);
Person p = new Person("张三",1);
Person p1 = new Person("张三",2);
Person p2 = new Person("张四",2);
Person p3 = new Person("张四",2);

TreeSet<Person> treeSet=new TreeSet<Person>();

Iterator<Person> iterator = treeSet.iterator();
while(iterator.hasNext()){
Person next = iterator.next();
System.out.println(next);
}
}
}
class Person implements Comparable<Person>{//该接口强制让人具有比较性
private String name;
private int age;
public Person(String name,int age) {
this.name = name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Person o) {
if(this.age>o.age){
return 1;
}else if(this.age<o.age){
return -1;
}else{
return this.name.compareTo(o.name);
}
}
@Override
public String toString() {
return "Person [name=" + name +  ", age=" + age + "]";
}
}``````

``````import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
*
* @author WangShuang
*
*/
public class Demo {
public static void main(String[] args) {
Person p0 = new Person("张三",3);
Person p = new Person("张三",1);
Person p1 = new Person("张三",2);
Person p2 = new Person("张四",2);
Person p3 = new Person("张四",2);

TreeSet<Person> treeSet=new TreeSet<>(new Com());

Iterator<Person> iterator = treeSet.iterator();
while(iterator.hasNext()){
Person next = iterator.next();
System.out.println(next);
}
}
}
class Com implements Comparator<Person>{//该接口强制让集合具有比较性
@Override
public int compare(Person o1, Person o2) {
if(o1.getAge()>o2.getAge()){
return 1;
}else if(o1.getAge()<o2.getAge()){
return -1;
}else{
return o1.getName().compareTo(o2.getName());
}
}
}

class Person{
private String name;
private int age;
public Person(String name,int age) {
this.name = name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name +  ", age=" + age + "]";
}
}``````