public class Log {public Integer id;public String name;public Date time;get.set.......}List<Log> logs = new ArrayList<Log>(); 我如何跟据Log里面的time对List进行正序或者倒序?
1. implements Comparable public class Log implements Comparable{ long time; public int compareTo(Log o) { return this.time - o.time; } } 2. sort List<Log> logs = new ArrayList<Log>(); ..... Collections.sort(logs);
sort List<Log> logs = new ArrayList<Log>(); ..... Collections.sort(logs);
class Log implements Comparable,Serializable{ /** * */ private static final long serialVersionUID = 1L; private Date time; public Date getTime(){ return this.time; } public Log(Date time){ this.time = time; } public int compareTo(Object o) { if(!(o instanceof Log)){ throw new ClassCastException(o.getClass().getName()); }else{ Log log = (Log)o; return this.getTime().compareTo(log.getTime()); } }
} public void test(){ List<Log> list = new ArrayList<Log>(); Log log = new Log(new Date(new Date().getTime()+10000)); Log log1 = new Log(new Date()); list.add(log); list.add(log1); for (Log log2 : list) { System.out.println(log2.getTime()); } System.out.println("kkkkkkkkkkkkkkkk"); Collections.sort(list); for (Log log2 : list) { System.out.println(log2.getTime()); } }
public class Log implements Comparable{
long time;
public int compareTo(Log o) {
return this.time - o.time;
}
}
2. sort
List<Log> logs = new ArrayList<Log>();
.....
Collections.sort(logs);
List<Log> logs = new ArrayList<Log>();
.....
Collections.sort(logs);
/**
*
*/
private static final long serialVersionUID = 1L;
private Date time; public Date getTime(){
return this.time;
}
public Log(Date time){
this.time = time;
}
public int compareTo(Object o) {
if(!(o instanceof Log)){
throw new ClassCastException(o.getClass().getName());
}else{
Log log = (Log)o;
return this.getTime().compareTo(log.getTime());
}
}
}
public void test(){
List<Log> list = new ArrayList<Log>();
Log log = new Log(new Date(new Date().getTime()+10000));
Log log1 = new Log(new Date());
list.add(log);
list.add(log1);
for (Log log2 : list) {
System.out.println(log2.getTime());
}
System.out.println("kkkkkkkkkkkkkkkk");
Collections.sort(list);
for (Log log2 : list) {
System.out.println(log2.getTime());
}
}
List 有排序方法的。java带的有。