- import java.util.TreeSet;
- class TreeSetDemo3
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Student(39));
- /*ts.add(new Student(52));
- ts.add(new Student(29));
- ts.add(29);
- ts.add(38);
- ts.add(29);
- ts.add(14);*/
- //System.out.println(new Student(22)+"+88");
- System.out.println(ts); //输出结果[14, 29, 30, 38]
- }
- }
- class Student implements Comparable
- {
- private int age;
- Student(int age)
- {
- this.age = age;
- }
- // 覆写Comparable接口中的比较器
- public int compareTo(Object obj)
- {
- Student stu = (Student)obj;
- // obj这里是一个实例化匿名对象,例如new Student(22)
- System.out.println(stu.age);
- if (this.age > stu.age)
- {
- return 1;
- }
- if (this.age < stu.age)
- {
- return -1;
- }
- return 0;
- }
- public String toString()
- {
- return age; // 提示return的返回值类型打印时提示不一致
- }
- }
复制代码 但是,以下这个程序写法几乎一模一样。确运行正常。帮忙指导一下 我哪里写错了。- import java.util.TreeSet;
-
-
- class TreeSetDemo2
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
-
- ts.add(new Student("lisi0",30));
- ts.add(new Student("lisixx",29));/*
- ts.add(new Student("lisi9",29));
- ts.add(new Student("lisi8",38));
- ts.add(new Student("lisixx",29));
-
- */
-
- System.out.println(ts);
- }
- }
-
- //同姓名同年龄的学生视为同一个学生。按照学生的年龄排序。
- class Student implements Comparable
- {
- private int age;
- private String name;
- Student(String name,int age)
- {
- this.age = age;
- this.name = name;
-
- }
-
- public int compareTo(Object obj)
- {
-
- /
- Student stu = (Student)obj;
-
- if(this.age>stu.age)
- return 1;
- if(this.age==stu.age)
- return 0;
- return -1;
-
-
- }
-
-
- public String toString()
- {
- return name+"::"+age;
- }
- }
复制代码 |