# Collection集合--对List集合元素排序的两种方法

### 二、代码实现

##### 2.1、List中的元素自己实现一个Comparable接口实现一个自然排序

package CollectionLearn;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
* Created by luckyboy on 2018/7/29.
*/
public class SortList {
private List<Person> list = new ArrayList<Person>();

private Person p1 = new Person(2,"name1");
private Person p2 = new Person(3,"name3");
private Person p3 = new Person(1,"name4");
private Person p4 = new Person(4,"name2");

@Test
public void testCommonType_I(){
list.sort(null);//传入的Comparator=null，实现自然排序
//遍历集合
list.forEach(item->{
System.out.println(item.toString());
});
}
}
class Person implements Comparable{
int age;
String name;
public Person(){};
public Person(int age,String name){
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Object o) {
Person p = (Person)o;
if(this.getAge()-p.getAge()<0){
return -1;
}
if(this.getAge()-p.getAge()>0){
return 1;
}
return 0;
}
}

Person{age=1, name='name4'}
Person{age=2, name='name1'}
Person{age=3, name='name3'}
Person{age=4, name='name2'}

java.lang.ClassCastException: CollectionLearn.Person cannot be cast to java.lang.Comparable

at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.util.Arrays.sort(Arrays.java:1312)
at java.util.Arrays.sort(Arrays.java:1506)
at java.util.ArrayList.sort(ArrayList.java:1460)
##### 2.2、我们通过实现一个Comparator接口的类对Person对象进行排序
/**
class PersonNameComparator implements Comparator<Person>{

@Override
public int compare(Person o1, Person o2) {
return o1.compareTo(o2);
}

@Override
public Comparator reversed() {
return null;
}

@Override
public Comparator thenComparing(Comparator other) {
return null;
}

@Override
public Comparator thenComparingInt(ToIntFunction keyExtractor) {
return null;
}

@Override
public Comparator thenComparingLong(ToLongFunction keyExtractor) {
return null;
}

@Override
public Comparator thenComparingDouble(ToDoubleFunction keyExtractor) {
return null;
}

@Override
public Comparator thenComparing(Function keyExtractor) {
return null;
}

@Override
public Comparator thenComparing(Function keyExtractor, Comparator keyComparator) {
return null;
}
}

    @Test
public void testCommonType_II(){
}