本帖最后由 王宝龙 于 2012-9-25 20:46 编辑
首先定义了一个Person类,然后定义Student类并继承Person类 。定义了Person对象和Student对象存入TreeSet中
Person类中有自己的compareTo方法 Student中也有自己的compareTo方法
存入不同的类对象之间不用排序吗?如果排序是怎么排的?- import java.util.*;
- class TreeSetDemo8
- {
- public static void main(String[] arge)
- {
- TreeSet ts = new TreeSet();
-
- ts.add(new Person("Perlisi00",24));
-
- ts.add(new Person("Perlisi02",23));
- ts.add(new Student("Stulisi07",43));
- ts.add(new Student("Stulisi08",40));
- ts.add(new Person("Perlisi03",21));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Person p = (Person)it.next();
- sop(p.getName()+"^^^^^^^^"+p.getAge());
- }
- Person p1 = new Person("zhangsan",18);
- sop(p1.toString());
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Person implements Comparable//定义一个Person类
- {
- private String name;
- private int age;
- public Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public int compareTo(Object obj)//按年龄排序
- {
- if(!(obj instanceof Person))
- throw new RuntimeException("不是人对象");
-
- Person p = (Person)obj;
-
-
- if(this.age>p.age)
- return 1;
- if(this.age==p.age)
- {
- return this.name.compareTo(p.name);
- }
- return -1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class Student extends Person
- {
- public Student(String name,int age)
- {
- super(name,age);
- }
- public int compareTo(Object obj)//按姓名排序
- {
- if(!(obj instanceof Person))
- throw new RuntimeException("不是人对象");
-
- Person p = (Person)obj;
-
- int num = this.getName().compareTo(p.getName());
- if(num==0)
- {
- return this.getAge()-p.getAge();
- }
- return num;
- }
- public String getName()
- {
- return super.getName();
- }
- public int getAge()
- {
- return super.getAge();
- }
-
-
- }
复制代码 |