此类将向您展示 Comparable 接口的实现,并使用 Collections.sort 方法根据文件名对列表进行排序。
package com.roka.tgpl.sms;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MyFile implements Comparable<MyFile> {
private String name;
private Date lastModified;
private int size;
MyFile(String name,Date lastModified,int size){
this.name = name;
this.lastModified =lastModified;
this.size = size;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the lastModified
*/
public Date getLastModified() {
return lastModified;
}
/**
* @param lastModified the lastModified to set
*/
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
/**
* @return the size
*/
public int getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(int size) {
this.size = size;
}
public int compareTo(MyFile o) {
int compare = this.name.compareTo(o.getName());
return compare;
}
public static void main(String arg []) {
List<MyFile> fileList = new ArrayList<MyFile>();
fileList.add(new MyFile("DCB", Calendar.getInstance().getTime(), 5));
fileList.add(new MyFile("ABC", Calendar.getInstance().getTime(), 15));
Collections.sort(fileList);
for(MyFile file : fileList){
System.out.println(file.getName());
}
}
}