当你存哪个对象的时候,就调用哪个对象的compareTo()方法。
例子如下:
main方法
package com.octsix;
import java.util.Set;
import java.util.TreeSet;
public class CompareTest {
/**
* @param args
*/
public static void main(String[] args) {
Set ts = new TreeSet();
Person p1 = new Person("张大", 50);
Person p2 = new Person("王大", 50);
Student s1 = new Student("张小1", 20);
ts.add(p1);
ts.add(p2);
ts.add(s1);
}
}
Person类(父类)
package com.octsix;
public class Person implements Comparable{
//构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
int age;
String name;
public int compareTo(Object obj) {
Person p = (Person)obj;
int flag = this.name.compareTo(p.name);
if(flag == 0) {
flag = this.age - p.age;
}
System.out.println(this.name + "父类compareTo()");//标识调用方法
return flag;
}
}
Student类(子类)
package com.octsix;
public class Student extends Person{
//构造方法
public Student(String name, int age) {
super(name, age);
}
public int compareTo(Object obj) {
Person p = (Person)obj;
int flag = this.name.compareTo(p.name);
if(flag == 0) {
flag = this.age - p.age;
}
System.out.println(this.name + "子类compareTo()");//标识调用方法
return flag;
}
}
运行结果如下:
PS:
可能是因为我的网速问题,我点添加代码文字没有反应。只能这样看了。。
|