黑马程序员技术交流社区

标题: 求解答:instanceof的问题 [打印本页]

作者: 智远    时间: 2015-4-20 15:26
标题: 求解答:instanceof的问题
  1. public int compareTo(Object o) {
  2.                 if(!(o instanceof Person)){
  3.                          throw new RuntimeException("不是Person");
  4.                 }
  5.                 Person p=(Person) o;
  6.                 if (this.age>p.age) {
  7.                         return 1;
  8.                 }
  9.                 if (this.age==p.age) {
  10.                                 return this.name.compareTo(p.name);
  11.                 }
  12.                 return -1;
  13.         }
复制代码

                TreeSet ts=new TreeSet();
                ts.add("2");ts.add(new Person("d",2));ts.add(new Person("c",2));
我加了一个不是Person的对象,为什么没输出这一句: "不是Person"
作者: 一个好人    时间: 2015-4-20 15:27
我觉得是if   else if  .else这样写
作者: 智远    时间: 2015-4-20 15:31
一个好人 发表于 2015-4-20 15:27
我觉得是if   else if  .else这样写

不是这个关系,第一个if中我传一个“2”对象时,括号的结果应该是true才对,但是if里面的语句却没执行




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2