泛型和TreeSet的应用(一)

package cn.us;
import java.util.Iterator;
import java.util.TreeSet;
//泛型和TreeSet的应用(一)
//存入TreeSet集合中的元素是无序的,但有方法给它排序
//排序方式一:让元素自身具备比较性,需元素实现Comparable接口
//核心:重写Comparable接口的方法compareTo(Object obj)
//if (tea.age == this.age) //年纪相同时再按照姓名排序!!!
//         return this.name.compareTo(tea.name);
//因为String也类实现了此接口,当然就可以调用compareTo()方法
class Teacher implements Comparable {
	private int age;
	private String name;
	public Teacher(int age, String name) {
		this.age = age;
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public String getName() {
		return name;
	}
	@Override
	public String toString() {
		return "Teacher [age=" + age + ", name=" + name + "]";
	}
	@Override
	public int compareTo(Object obj) {//按照年纪排序
		Teacher tea = (Teacher) obj;
		if (tea.age < this.age) {
			return -1;
		}
		if (tea.age == this.age) {//年纪相同时再按照姓名排序!!!核心
			return this.name.compareTo(tea.name);
		}
		if (tea.age > this.age) {
			return 1;
		}
		return 0;
	}

}

public class Test4 {
  public static void main(String[] args) {
        Teacher teac1=new Teacher(25, "lim");
        Teacher teac2=new Teacher(26, "uim");
        Teacher teac3=new Teacher(55, "zim");
        Teacher teac4=new Teacher(55, "mim");
        Teacher teac5=new Teacher(55, "cim");
        TreeSet<Teacher> treeSet=new TreeSet<Teacher>();
        treeSet.add(teac1);
        treeSet.add(teac2);
        treeSet.add(teac3);
        treeSet.add(teac4);
        treeSet.add(teac5);
        Iterator<Teacher> iterator=treeSet.iterator();
        while(iterator.hasNext()){
        	//Teacher t=(Teacher) iterator.next();
        	Teacher t=iterator.next();//避免了上句的强转
        	System.out.println(t.getName()+"的年纪是"+t.getAge());
        }
  }
}

你可能感兴趣的:(泛型和TreeSet的应用(一))