用Collections.sort方法對list排序有兩種方法
第一種是list中的物件實作Comparable介面,如下:
[java] view plain copy
/**
* 依order對User排序
*/
public class User implements Comparable implements Comparable
private String name;
private Integer order;
}
public void setName(String name) {
this.name = name; ) {
return order;
}
public void set }
public int compareTo(User arg0) {
return this.getOrder().compareTo(arg0.getOrder() );
}
} 測試一下:
public class Test{
public );
user1.setName("a");
user1.setOrder (1);
User user2 = new User();
user2.setName(b"); List
//此處add user2再add user1
list.add(user2);
for(User u : list){
System.out.println(u.getName( ));
}
}
}
[java] view plain copy
/**
* 依order對User排序
*/
public class User { //此處無實作Comparable介面
private String name;
private Integer order; return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
(Integer order) {
this.order = order;
}
}
(HastSet——>List——>sort進行排序):
public class Test {
public static void main(String[] args) {
("a");
user1.setPrice(11);
User user2 = new User(); user2.setPrice(2);
Set
Hset.add(user2); List
list. addAll(Hset);
Collections.sort(list,new Comparator
return arg0.getPrice().compareTo(arg1.getPrice()) ;
}
});
println(u.getName());
}
}
輸出結果如下:
a
輸出結果如下:
a
b ,將。 return arg0.getOrder().compareTo(arg1.getOrder()); 改為:
return arg1.getOrder().compareTo(arg0.getOrder());
就成降序的了。