在工作中,碰到很多開發人員對於camparator接口理解都不深,每次做排序都要寫一個main函數試一下才知道就行排序對了沒。
怎麼理解這個接口的行爲
接口註釋原文:
Compares its two arguments for order. Returns a negative integer,
* zero, or a positive integer as the first argument is less than, equal
* to, or greater than the second.<p>
comparator接口(01,02)->{}
- 排序默認是按照升序排序
- 如果返回-1,就認爲01 小於02,(注意01和02的順序)
- 如果返回0,認爲兩個相等
- 如果返回1,就認爲01大於02,(注意01和02的順序)
這個方法有一個需要特別注意的點,一個是對於(01,02),(02,01)方法的行爲應該保持一致。 改方法內部使用的是歸併排序
怎麼實現多重排序
一開始自己沒想,就想google看看有沒有現成的,結果google出來質量堪憂。
於是就想着自己寫寫看,那直接看代碼好了。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* User:ThinerZQ
* Email:[email protected]
* Date:2016/9/23 14:37
* Project:Test
* Package:PACKAGE_NAME
*/
public class TestCompartor {
public static void main(String[] args) {
ArrayList<Person> persons = new ArrayList<Person>();
persons.add(new Person(10,1000,4));
persons.add(new Person(1,1020,5));
persons.add(new Person(1,1020,4));
persons.add(new Person(13,1100,2));
persons.add(new Person(1,1020,5));
for (int i = 0; i <persons.size(); i++) {
System.out.println(persons.get(i));
}
System.out.println();
Collections.sort(persons, new Comparator<Person>() {
//級別,年份,薪資排序降序,
public int compare(Person o1, Person o2) {
//只有級別相等的時候才用去判斷薪水
if (o1.level == o2.level){
//只有薪水相等的時候採用去判斷年份
if (o1.salary == o2.salary){
//最後按照年份判斷了。
return o2.years - o1.years;
}else{
//薪水不相等就按照薪水判斷嘛
return o2.salary - o1.salary;
}
}else{
//級別不相等就按照級別判斷嘛
return o2.level - o1.level;
}
}
});
for (int i = 0; i <persons.size(); i++) {
System.out.println(persons.get(i));
}
}
static class Person{
public int level; //級別
public int salary; //工資
public int years; //入職年數
@Override
public String toString() {
return "Person{" +
"level=" + level +
", salary=" + salary +
", years=" + years +
'}';
}
public Person(int level, int salary, int years) {
this.level = level;
this.salary = salary;
this.years = years;
}
}
}