本帖最后由 张晓辉 于 2013-9-11 16:25 编辑
- import java.util.*;
- class student implements Comparable
- {
- private String name;
- private int age;
- student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public String getName()
- {return name;}
- public int getAge()
- {
- return age;
- }
- public int compareTo(Object obj)
- {
- if (!(obj instanceof student))
- {
- throw new RuntimeException("不是学生对象");
- }
- student s=(student)obj;
- if (this.age>s.age)
- {
- return 1;
- }
- if (this.age==s.age)
- {
- return this.name.compareTo(s.name);
- }
- return -1;
- }
- }
- class treesetlianxi
- {
- public static void main(String[] args)
- {
- TreeSet al=new TreeSet();
- al.add(new student("jack001",20));
- al.add(new student("jack002",20));
- al.add(new student("jack001",20));
- al.add(new student("jack003",21));
- al.add(new student("jack004",10));
- Iterator it=al.iterator();
- while (it.hasNext())
- {
- student s=(student)it.next();
- System.out.println(s.getName()+"-----"+s.getAge());
- }
- }
- }
复制代码 在student类覆写Comparable接口compareTo()方法中- if (!(obj instanceof student))
- {
- throw new RuntimeException("不是学生对象");
- }
复制代码 不一样的对象,会抛出异常,求个验证过的实例。
|