本帖最后由 刘茂林 于 2013-5-14 11:54 编辑
- import java.util.*;
- import java.lang.*;
- /*
- * 实现在容器TreeSet中存入自定义对象
- *
- * 比如存个学生 学生有姓名年龄属性 并按照年龄进行排序
- * */
- public class TreeSetDemo
- {
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
-
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Person("lisi02",22));//
- //ts.add(new Person("lisi007",27));
- //ts.add(new Person("lisi05",28));
- //ts.add(new Person("lisi09",21));
-
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName() + "......" + stu.getAge());
- }
- }
- }
- 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)//必须重写comparTo方法
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象");
-
- Student s = (Student)obj;
-
- if(this.age > s.age)
- return 1;
- if(this.age == s.age)
- return 0;
- return -1;
- }
- }
复制代码 一直出现问题 没照出来哪里错了 多谢帮助了 |
|