針對list裏對象屬性的排序問題

import java.util.Date;

public class Customer{
   private String name;
   private int    age;
   private int lev;
   private Date   inTime; 
   
   public Customer(String name, int age, int lev, Date inTime) {
super();
this.name = name;
this.age = age;
this.lev = lev;
this.inTime = inTime;
   }
  public Customer() {
super();
  }
  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;
  }
  public int getLev() {
return lev;
  }
  public void setLev(int lev) {
this.lev = lev;
  }
  public Date getInTime() {
return inTime;
  }
  public void setInTime(Date inTime) {
this.inTime = inTime;
  }
   

}


import java.util.Comparator;

public class ComparatorCus implements  Comparator {
@Override
public int compare(Object o1, Object o2) {
Customer cus1 = (Customer)o1;
Customer cus2 = (Customer)o2;

                //排序的優先級是等級、再是時間
int flag = cus1.getLev()-cus2.getLev(); //若不是int類型,可以這樣比較int flag = cus1.getLev().compareTo(cus2.getLev());
if(flag==0){//等級相等
return (cus1.getInTime().after(cus2.getInTime()))==true?1:-1;
}else{
return flag;
}

}

}


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class SortCusTest {

public static void main(String[] args) throws Exception {
List<Customer> list = new ArrayList<Customer>();
SimpleDateFormat formater= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
list.add(new Customer("zhang",20,1,formater.parse("2015-3-23 10:10:00")));
list.add(new Customer("wang",22,2,formater.parse("2015-3-23 10:10:10")));
list.add(new Customer("li",19,2,formater.parse("2015-3-23 10:10:05")));
list.add(new Customer("zhao",30,1,formater.parse("2015-3-23 10:10:08")));
list.add(new Customer("chang",20,2,formater.parse("2015-3-23 10:10:15")));

ComparatorCus copm = new ComparatorCus();
Collections.sort(list, copm);
for(Customer c:list){
System.out.println("Name:"+c.getName()+", Lev:"+c.getLev()+", Date:"+formater.format(c.getInTime()));
}
}

}


結果:

Name:zhang, Lev:1, Date:2015-03-23 10:10:00
Name:zhao, Lev:1, Date:2015-03-23 10:10:08
Name:li, Lev:2, Date:2015-03-23 10:10:05
Name:wang, Lev:2, Date:2015-03-23 10:10:10
Name:chang, Lev:2, Date:2015-03-23 10:10:15

發佈了30 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章