日期:2014-05-20 浏览次数:21024 次
package bt_lose; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 简单实体 * * @author botao * */ public class User { @Override public String toString() { return "User: id=" + uid + " uname=" + uname + " upass=" + upass; } private int uid; private String uname; private String upass; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpass() { return upass; } public void setUpass(String upass) { this.upass = upass; } public User() { } public User(int id, String name, String pass) { this.uid = id; this.uname = name; this.upass = pass; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public static void main(String[] args) { List<User> list = new ArrayList<User>(); list.add(new User(1, "name1", "pass1")); list.add(new User(3, "name3", "pass3")); list.add(new User(2, "name2", "pass2")); list.add(new User(4, "name4", "pass4")); System.out.println("before sort"); for (User user : list) { System.out.println(user); } //比较器是通过匿名类来做的 Collections.sort(list, new Comparator<User>() { public int compare(User arg0, User arg1) { //定义如何比较 return arg0.getUid() - arg1.getUid(); } }); System.out.println("after sort"); for (User user : list) { System.out.println(user); } } }
------解决方案--------------------
package test1.sort;
import java.util.Comparator;
public class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
MyObject obj1 = (MyObject) o1;
MyObject obj2 = (MyObject) o2;
return obj1.getStartTime().before(obj2.getStartTime())?1:0;
}
}
package test1.sort;
import java.util.Date;
public class MyObject {
private int id;
private Date startTime;
private String ani;
public MyObject(int id,Date startTime,String ani) {
this.id = id;
this.startTime = startTime;
this.ani = ani;
}
public String getAni() {
return ani;
}
public void setAni(String ani) {
this.ani = ani;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
}
package test1.sort;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
/**
* @param args
* @throws ParseException