class User {
String name;
String age;
public User(String name,String age){
this.name=name;
this.age=age;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//具体的比较类,实现Comparator接口
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class ComparatorUser implements Comparator{
public int compare(Object arg0, Object arg1) {
User user0=(User)arg0;
User user1=(User)arg1;
//首先比较年龄,如果年龄相同,则比较名字
int flag=user0.getAge().compareTo(user1.getAge());
if(flag==0){
return user0.getName().compareTo(user1.getName());
}else{
return flag;
}
}
}
//测试类
public class SortTest {
public static void main(String[] args){
List userlist=new ArrayList();
userlist.add(new User("dd","4"));
userlist.add(new User("aa","1"));
userlist.add(new User("ee","5"));
userlist.add(new User("bb","2"));
userlist.add(new User("ff","5"));
userlist.add(new User("cc","3"));
userlist.add(new User("gg","6"));
ComparatorUser comparator=new ComparatorUser();
Collections.sort(userlist, comparator);
for (int i=0;i<userlist.size();i++){
User user_temp=(User)userlist.get(i);
System.out.println(user_temp.getAge()+","+user_temp.getName());
}
}
}
//首先年龄排序,如果年龄相同,则按名字排序
结果:
1, aa
2, bb
3, cc
4, dd
5, ee //注意:同样是5岁的人,则比较名字(ee,ff),然后排序
5, ff
6, gg
第二种
/**
* 根据order对User排序
*/
public class User { //此处无需实现Comparable接口
private String name;
private Integer order;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
}
public class Test{
public static void main(String[] args) {
User user1 = new User();
user1.setName("a");
user1.setOrder(1);
User user2 = new User();
user2.setName("b");
user2.setOrder(2);
List<User> list = new ArrayList<User>();
list.add(user2);
list.add(user1);
Collections.sort(list,new Comparator<User>(){
public int compare(User arg0, User arg1) {
return arg0.getOrder().compareTo(arg1.getOrder());
}
});
for(User u : list){
System.out.println(u.getName());
}
}
}