黑马程序员技术交流社区
标题:
TreeSet的用法疑问
[打印本页]
作者:
吴健
时间:
2012-12-10 12:33
标题:
TreeSet的用法疑问
TreeSet 里面放对象,如果同时放入了父类和子类的实例对象,那比较时使用的是父类的
compareTo 方法,还是使用的子类的 compareTo 方法,还是会抛异常?
作者:
xjandrew
时间:
2012-12-11 02:04
本帖最后由 xjandrew 于 2012-12-12 01:13 编辑
结果会抛异常
import java.util.*;
public class TreesetTest
{
public static void main(String[] args)
{
//TreeSet<? extends Person> ts = new TreeSet<Student>();//执行这句的话,add方法报错,类型不匹配
ts.<FONT color=red>add</FONT>(new Person("zhangsan",23));
ts.<FONT color=red>add</FONT>(new Person("zhangsan",22));
TreeSet<? super Student> ts = new TreeSet<Student>();//执行这句话,Person报错,类型转换异常(Person无法转成Student)
ts.add((Student) new Person("zhangsan",23));
ts.add((Student) new Person("zhangsan",22));
ts.add(new Student("zhangsan",23,3));
ts.add(new Student("zhangsan",22,2));
}
}
class <FONT color=red>Person</FONT> implements Comparable<Student>
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Person p)
{
int num = this.name.compareTo(p.getName());
if(num == 0)
return new Integer(this.age).compareTo(new Integer(p.getAge()));
return num;
}
@Override
public int compareTo(Student o) //这里还必须留给子类重写
{
// TODO Auto-generated method stub
return 0;
}
}
class Student extends Person //implements Comparable<Student>加这句不行
{
private int nianji;
Student(String name,int age,int nianji)
{
super(name,age);
this.nianji = nianji;
}
public int compareTo(Student s)
{
int num = new Integer(this.nianji).compareTo(new Integer(s.getNianji()));
return num;
}
public int getNianji()
{
return nianji;
}
}
*
复制代码
作者:
xjandrew
时间:
2012-12-11 02:14
按以上代码来看,无法同时放入父类和子类的实例对象
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2