jsp教程 list排序的問題代碼-jsp入門
個list a和b,分別存有對象ob1,ob2。這兩個對象裡都有一個日期類型的欄位createTime。
現在要將a和b存入listc中,然後按照日期欄位createTime的值進行排序,
方法一
把你的對象實現Comparable介面,然後調用Collections.sort()方法就可以
利用自訂函數
package com.xuz.datastruct.csdn;
import java.util.Date;
public class MyClass implements Comparable<MyClass> {
private Date d;
public MyClass(Date d) {
this.setD(d);
}
@Override
public String toString(){
return "my value is " + d;
}
@Override
public int compareTo(MyClass o) {
if (d.after(o.getD())) {
return -1;
}
if (d.before(o.getD())) {
return 1;
}
return 0;
}
public void setD(Date d) {
this.d = d;
}
public Date getD() {
return d;
}
}
Collections.sort(list);
方法三
package com.xuz.datastruct.csdn;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class CompareList {
public static void main(String[] args) throws InterruptedException {
List<MyClass> list = new ArrayList<MyClass>();
list.add(new MyClass(Calendar.getInstance().getTime()));
Thread.sleep(1000);
list.add(new MyClass(Calendar.getInstance().getTime()));
Thread.sleep(1000);
list.add(new MyClass(Calendar.getInstance().getTime()));
Thread.sleep(1000);
list.add(new MyClass(Calendar.getInstance().getTime()));
Thread.sleep(1000);
list.add(new MyClass(Calendar.getInstance().getTime()));
Thread.sleep(1000);
for (MyClass myClass : list) {
System.out.println(myClass);
}
System.out.println();
Collections.sort(list);
for (MyClass myClass : list) {
System.out.println(myClass);
}
}
}