黑马程序员技术交流社区
标题:
集合TreeSet比较器里面抛异常的问题。
[打印本页]
作者:
曹德君
时间:
2013-4-26 11:50
标题:
集合TreeSet比较器里面抛异常的问题。
本帖最后由 曹德君 于 2013-4-26 21:03 编辑
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Person("lisi001",10));
ts.add(new Person("lisi002",20));
ts.add(new Person("lisi003",30));
ts.add(new Person("lisi004",40));
ts.add(new Person("lisi007",40));
ts.add(new Person("lisi002",40));
for (Iterator it=ts.iterator();it.hasNext(); )
{
//Object obj =it.next();这里有类型提升。必须强转成Person才能输出名字和年龄。
Person p = (Person)it.next();
sop(p.getName()+"..m.."+p.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Person implements Comparable
{
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(Object obj)
{
if (!(obj instanceof Person))
{
throw new RuntimeException("不是Person对象");//1疑问这里为什么要抛出RuntimeException异常?用horows抛为什么不行??
}
Person p=(Person)obj;
if (this.age>p.age)
return 1;
if (this.age==p.age)
//字符串本身也具备比较性String类里面的comparaTo()方法
return this.name.compareTo(p.name);
return -1;
}
}
复制代码
作者:
932759732
时间:
2013-4-26 11:56
if (!(obj instanceof Person))
{
throw new RuntimeException("不是Person对象");//1疑问这里为什么要抛出RuntimeException异常?用horows抛为什么不行??
}
Person p=(Person)obj;
直接抛出RuntimeException是可以终止程序的。
如果这个地方接收进来的不是一个Person对象那这段代码就失去了意义,就没有执行下去的必要了。所以选择终止程序。
而且补充一下。RuntimeException是不可以throws的。
作者:
孙浩
时间:
2013-4-26 12:36
本帖最后由 孙浩 于 2013-4-26 12:38 编辑
RuntimeException可以抛也可以不抛,编译器不检查该类的子异常!你这里不能抛是因为: compareTo(obj)方法是实现Comparable接口的方法,在Comparable接口中没有抛出任何异常,那么在它的实现类中只能处理!因为:子类方法声明的异常范围只能小于或等于父类方法所声明的异常!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2