62,620
社区成员
发帖
与我相关
我的任务
分享



public class App {
static class TestClass{
private Date date;
private String time;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public TestClass(Date date, String time) {
super();
this.date = date;
this.time = time;
}
}
public static void main(String[] args) {
TestClass c1 = new TestClass(new Date(2017, 3, 20), "1");
TestClass c2 = new TestClass(new Date(2017, 3, 19), "2");
TestClass c3 = new TestClass(new Date(2017, 3, 21), "3");
TestClass c4 = new TestClass(new Date(2017, 2, 15), "4");
List<TestClass> list = Arrays.asList(c1,c2,c3,c4);
System.out.println("排序前:");
for (TestClass testClass : list) {
System.out.println(testClass.date + ":" + testClass.time);
}
//排序
Collections.sort(list, new Comparator<TestClass>() {
@Override
public int compare(TestClass o1, TestClass o2) {
return o1.getDate().compareTo(o2.getDate()); //按日期排序
}
});
System.out.println("排序后:");
for (TestClass testClass : list) {
System.out.println(testClass.date + ":" + testClass.time);
}
}
}
@Override
public int compareTo(Field o) {
// 先按age排序
if (this.age > o.getAge()) {
return (this.age - o.getAge());
}
if (this.age < o.getAge()) {
return (this.age - o.getAge());
}
// 按name排序
if (this.name.compareTo(o.getName()) > 0) {
return 1;
}
if (this.name.compareTo(o.getName()) < 0) {
return -1;
}
return 0;
}
然后使用 compareTo 进行比较排序,
排序算法 可以用冒泡排序法(不懂的话,参看 http://www.cnblogs.com/wuzhenbo/archive/2012/03/30/2423861.html)