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

TreeSet中remove依据哪些方法来执行的?
由于本人自学无指导,所以问题可能简单些,我自己调试了又上网百度还是没找到满意的答案,希望大神们多多指点。
错误代码如下(编译通过,运行抛异常):
class Student implements Comparable//该接口让学生强制具有比较性
{
//成员属性及setget方法就不写出来了
        
        //疑问1:
         //equals方法:API文档中提示remove依据的是equals方法,但教学视频中讲解依据compareTo

        public boolean equals(Object obj)
{

                if(!(obj instanceof Student))
throw new RuntimeException("该对象不是学生") ;

Student stu = (Student)obj;

if(this.name.equals(stu.name))
{
if(this.age==stu.age)
return true;
}

return false;
}

public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("该对象不是学生") ;

Student st = (Student)obj;
int i =this.name.compareTo(st.name);
System.out.println(this.name+"compareto........"+st.name+i);
if(i==0)
return this.age-st.age;
else
return i;
}

}
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();

ts.add(new Student("student01",23));
ts.add(new Student("student02",21));
ts.add(new Student("student01",22));

//疑问2:无论依据的是equals还是compareTo,都已重写或覆盖,请详细描述出错处
                ts.remove(new Person("student01",22));//异常代码行                  
}

public static void sop(Object obj)
{
System.out.println(obj);
}
}
TreeSet???remove

------解决方案--------------------
1, 删除根据compareTo
2, 代码没什么问题 你是不是笔误了 怎么变成了Person了