java运用Comparator为对象排序

要排序的类需要实现Comparator接口,重写compare方法:

user类及实现接口的内部类:

package test;

import java.util.Comparator;

public class User {
	private String userName;
	private int age;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "User [userName=" + userName + ", age=" + age + "]";
	}

}



test:

package test;

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

import org.junit.Test;

public class TestSort {
	@Test
	public void main() {
		// TODO Auto-generated method stub
		User user1 = new User();
		user1.setUserName("ddd");
		user1.setAge(20);
		User user2 = new User();
		user2.setUserName("aaa");
		user2.setAge(30);
		User user3 = new User();
		user3.setUserName("ccc");
		user3.setAge(15);
		User user4 = new User();
		user4.setUserName("bbb");
		user4.setAge(20);
		List<User> users = new ArrayList<User>();
		users.add(user1);
		users.add(user2);
		users.add(user3);
		users.add(user4);
		Collections.sort(users, new MyComparator());
		for (User user : users) {
			System.out.println(user);
		}
	}

	class MyComparator implements Comparator {
		public int compare(Object obj1, Object obj2) {
			User u1 = (User) obj1;
			User u2 = (User) obj2;
			if (u1.getAge() > u2.getAge()) {
				return 1;
			} else if (u1.getAge() < u2.getAge()) {
				return -1;
			} else {
				// 利用String自身的排序方法。
				// 如果年龄相同就按名字进行排序
				return -u1.getUserName().compareTo(u2.getUserName());
			}
		}
	}
}


你可能感兴趣的:(java)