????1. Comparator ?? Comparable ???????
???????????java????????? ??????????????????class????С???
?????????????class: ?? public class Person{ String name; int age }.
??????????????????personList???????????person1?? person2?? persion3.....?? ??????Collections.sort( personList )?? ??ò???????????. ?????????????? ?????????????????????list??:
?????? StringList{"hello1" ?? "hello3" ?? "hello2"}?? Collections.sort( stringList ) ??????????????? ??????? String ????????????????????? Comparable??? ?? ????????? Person ????????? ???????????????
????2. Comparator ?? Comparable ??????
????Comparable??
????Comparable ?????? Person??????:
????public class Persion implements Comparable {..???Person???С..}??
?????????????????????????????Person????????????????С??????????????????String???????????????????????????С?????Person???????????д?С?????Collections.sort(personList)???????????????
????Comparator??
????Comparator ???????Person??????? ????????Person????????????κα仯????
????public class Person{ String name; int age }??
?????????????????????????:
????public PersonComparator implements Comparator() {..???Person???С..}??
??????PersonComparator???????????????????Person???С. ???????????????????????????? personList???????????? ??????????????personList????? ???????PersonComparator?????????????????Person???С????PersonComparator????????? ??:
????Collections.sort( personList ?? new PersonComparator() ).
????3. Comparator ?? Comparable ?????
????Comparable:
???????Comparable????????compareTo?????? ??compareTo??????????????
<span style="font-size:14px;">//????????д?????????????????public class implements Comparable<Person>{...}
public class Person implements Comparable {
String name;
int age
public int compareTo(Person another) {
int i = 0;
i = name.compareTo(another.name); // ????????????
if(i == 0) { // ??????????????????? ????????????
return age - another.age;
} else {
return i; // ?????????? ?????????????.
}
}
}</span>
??????????????????? Collections.sort( personList ) ??????????.
????Comparator:
???????Comparator??????? compare ??????
<span style="font-size:12px;background-color: rgb(255?? 255?? 255);">public class Person{
String name;
int age
}
class PersonComparator implements Comparator { //?????????????????????...implements Comparator<Person>{...}
public int compare(Person one?? Person another) {
int i = 0;
i = one.name.compareTo(another.name); // ????????????
if(i == 0) { // ???????????????????????????????
return one.age - another.age;
} else {
return i; // ?????????? ?????????????.
}
}
}</span>
Collections.sort( personList ?? new PersonComparator()) ???????????