//1.新建一个实体类User
public class User {
String name;
Integer age;
public User(String name, Integer age) {
super();
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
//2.具体的比较类,实现Comparator接口
import java.util.Comparator;
/**
* @version 创建时间:2011-10-17 上午09:52:28
* 类说明
*/
public class ComparatorUser implements Comparator {
@Override
//首先比较年龄,如果年龄相同,则比较名字
public int compare(Object o1, Object o2) {
User user1 = (User)o1;
User user2 = (User)o2;
int flag = (user1.getAge()).compareTo(user2.getAge());
if (flag == 0) {
return user1.getName().compareTo(user2.getName());
} else {
return flag;
}
}
}
//3.排序测试类
package com.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortTest {
/**
* @param args
*/
public static void main(String[] args) {
List<User> userlist = new ArrayList<User>();
userlist.add(new User("aa",4));
userlist.add(new User("dd",8));
userlist.add(new User("cc",3));
userlist.add(new User("ff",4));
userlist.add(new User("bb",41));
userlist.add(new User("jj",1));
userlist.add(new User("nn",5));
ComparatorUser comparatorUser = new ComparatorUser();
Collections.sort(userlist, comparatorUser);
for (User user : userlist) {
System.out.println(user.getAge()+"*****"+user.getName());
}
// for (int i=0; i<userlist.size(); i++) {
// User user_temp = (User)userlist.get(i);
// System.out.println(user_temp.getAge() + "====" + user_temp.getName());
// }
}
}
来源:http://www.dream-chase.com
java List 排序实例详解 java环境变量配置
Java 获取路径 Chase_Java容器遍历的方法
java入门 Java菱形
Java倒三角 Java九九乘法表
java-俄罗斯方块 猜数字