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);
}
}}