日期:2014-05-20  浏览次数:20637 次

这个程序为什么会有类型转换错误?
import java.util.*;

public class Test
{
public static void main(String[] args)
{
SortedSet<A> list = new TreeSet<A>();
list.add(new A("abc", 100));
list.add(new A("efg", 102));
list.add(new A("bcd", 101));
list.add(new A("ccc", 99));
System.out.println(list);

}
}

class A implements Comparable<Object>
{
public A(String nmae, int age)
{
this.name = name;
this.age = age;
}

public String getName()
{
return name;
}

public int getAge()
{
return age;
}

public int compareTo(Object other)
{
A x = (A)other;
if(age > compareTo(x.age))
{
return 1;
}
else if(age == (x.age))
{
return 0;
}
else
{
return -1;
}
}

public String toString()
{
return "[ name=" + name + ", age=" + age + "]";
}
private String name;
private int age;


}

错误提示为

------解决方案--------------------
age > compareTo(x.age)

x.age是int 不能转为A类型

应该是 a > x.age吧?
------解决方案--------------------
if(age > compareTo(x.age))         {             return 1;             }             else if(age == (x.age))         {             return 0;   
    你这是几个意思??自己调用自己??递归??  还把x.age转成A  
------解决方案--------------------
1楼才是正解