本帖最后由 kerner 于 2014-12-2 15:34 编辑
以后发帖记得用代码格式,这样会容易让别人阅读。
首先,你的代码好多都是错误的啊,这都不能被编译过。
问题在于 T_Person2继承Person,那么T_Person2类中也具有Person的成员,但是它被T_perosn2类中自己定义的成员隐藏了
- public int compareTo(Person o) {
复制代码
这是访问父类中的成员属性,所以出现这个错误。
正确代码。- import java.util.Iterator;
- import java.util.TreeSet;
- class People
- {
- String name;
- int age;
-
- public People(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public People(){}
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
-
- }
- class T_Person2 extends People implements Comparable<T_Person2>
- {
- String name;
- int age;
-
- public T_Person2(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public T_Person2(){}
-
-
- public int compareTo(T_Person2 o) {
- System.out.println("T_Person=========");
- System.out.println("ta:"+this.age +" oa:"+o.age); //问题主要在这~~~ ta:11 oa:0 为什么 oa 输出结果一直都是0,
- //People o 不 能获得对象?
- if(this.age == o.age)
- {
- String tN = this.name;
- String oN = o.name;
- System.out.println("tn:"+tN +" oN:"+oN);
- return tN.compareTo(oN);
- }
- return new Integer(this.age).compareTo(new Integer(o.age));
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
-
- }
- public class ComparableClass {
- public static void main(String[] args) {
-
- TreeSet<T_Person2> p = new TreeSet<T_Person2>();
-
- p.add(new T_Person2("ee",11));
- p.add(new T_Person2("ss",12));
- p.add(new T_Person2("ee",11));
-
- print(p);
- }
- public static void print(TreeSet<? extends T_Person2> a)
- {
- Iterator<? extends T_Person2> it = a.iterator();
-
- while(it.hasNext())
- {
- T_Person2 t_Person = it.next();
- System.out.println("age:"+t_Person.getAge()+" name:"+t_Person.getName());
- }
- }
- }
复制代码
|