自定义对象排序

import java.util.HashMap;

public class Demo {

	public static void main(String[] args) {
		HashMap hm = new HashMap();
		hm.put(new Student("张三", 30), "基础班");
		hm.put(new Student("张三", 30), "基础班");
		hm.put(new Student("张三", 20), "基础班");
		hm.put(new Student("李四", 20), "基础班");
		System.out.println(hm.toString());
	}
}

class Student implements Comparable {

	String name;
	int age;

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return name + ":" + age;
	}

	@Override
	public int compareTo(Student o) {
		int num = this.name.compareTo(o.name);
		return num == 0 ? new Integer(this.age)
				.compareTo(new Integer(
						o.age))
				: num;
	}
}

你可能感兴趣的:(JAVA)