日期:2014-05-20 浏览次数:20766 次
public class Test {
public static void main(String[] args) throws Exception {
List<Lake> lakeList = new ArrayList<Lake>();
// 太湖
Lake taihuLake = new Lake();
taihuLake.setName("Taihu Lake");
taihuLake.setArea(2250);
// 鄱阳湖
Lake poYangLake = new Lake();
poYangLake.setName("Poyang Lake");
poYangLake.setArea(4400);
// 洞庭湖
Lake dongtingLake = new Lake();
dongtingLake.setName("Dongting Lake");
dongtingLake.setArea(2820);
// 洪泽湖
Lake hongzeLake = new Lake();
hongzeLake.setName("Hongze Lake");
hongzeLake.setArea(2069);
lakeList.add(taihuLake);
lakeList.add(poYangLake);
lakeList.add(dongtingLake);
lakeList.add(hongzeLake);
// 按名称排序
Comparator<Lake> c1 = new Comparator<Lake>() {
@Override
public int compare(Lake lake1, Lake lake2) {
return lake1.getName().compareTo(lake2.getName());
}
};
// 按面积排序
Comparator<Lake> c2 = new Comparator<Lake>() {
@Override
public int compare(Lake lake1, Lake lake2) {
return lake1.getArea() > lake2.getArea() ? 1 : -1;
}
};
Collections.sort(lakeList, c1);
for (Lake lake : lakeList) {
System.out.println(lake.getName());
}
Collections.sort(lakeList, c2);
for (Lake lake : lakeList) {
System.out.println(lake.getName());
}
}
}
class Lake {
/** 名称 */
private String name;
/** 面积 */
private int area;
public String getName() {