1. 程式人生 > >自定義物件排序

自定義物件排序

import java.util.HashMap;

public class Demo {

	public static void main(String[] args) {
		HashMap<Student, String> hm = new HashMap<Student, String>();
		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<Student> {

	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;
	}
}