list排序

主要编写比较类,在调用集合排序
package test;

import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

//比较类,实现Comparator接口
class ComparatorUser implements Comparator {
	public int compare(Object arg0, Object arg1) {
		User user0 = (User) arg0;
		User user1 = (User) arg1;

		// 比较age,如果age相同,则比较name
		int flag = user0.getAge().compareTo(user1.getAge());
		if (flag == 0) {
			return user0.getName().compareTo(user1.getName());
		} else {
			return flag;
		}
	}
}

// 测试类
public class SortTest {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		List<User> userlist = new ArrayList<User>();
		userlist.add(new User("dd", "4"));
		userlist.add(new User("aa", "1"));
		userlist.add(new User("ee", "5"));
        //创建比较类,调用集合接口排序
		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());
		}

	}
}

class User {
	private String name;
	private String age;

	public User(String name, String age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

}

你可能感兴趣的:(list排序)