JSP Tutorial List sort of problem code-jsp Getting Started
List A and B, with Object OB1,OB2 respectively. Both of these objects have a field createtime of the date type.
Now you want to save A and B in LISTC, and then sort by the value of the Date field Createtime,
Method One
implement the comparable interface for your object, and then call the Collections.sort () method to
Using Custom Functions
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 "I 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);
Method Three
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);
}
}
}