【问题标题】:null pointer exception after checking for null pointers检查空指针后出现空指针异常
【发布时间】:2014-05-03 11:28:55
【问题描述】:

尽管首先使用 if 语句检查值是否为空,但我得到一个空指针异常。这是我的代码:

Collections.sort(taskList,new Comparator<Task>(){ //here is one NPE
        @Override
        public int compare(Item t1,Item t2){
            if((t1.getAssignedString()!=null)&&(t2.getAssignedString()!=null)){ //here is second NPE
            int x=t1.getAssignedString().compareTo(t2.getAssignedString());

            if(x!=0){return x;}
            else{
                Integer x1=(int)(4*(((Task)t1).getAllottedTime()));
                Integer x2=(int)(4*(((Task)t2).getAllottedTime()));
                return x1.compareTo(x2);
            }
            }
            else{System.out.println("null value");
            return 0;}
        }

    });

为什么这个检查不起作用?有没有办法解决这个问题?

【问题讨论】:

  • 您正在检查t1.getAssignedString(),但不是t1

标签: java nullpointerexception


【解决方案1】:

你正在检查t1.getAssignedString()null,你需要检查t1!=null

对于t2的情况也是如此。

【讨论】:

    【解决方案2】:

    我猜您需要检查实际实例是否不为空,例如 taskList 和比较时的各个 Item 实例(t1 和 t2)。

    【讨论】:

      【解决方案3】:

      在使用 t1 和 t2 之前,你应该测试 t1 或 t2 是否不能为空

      Collections.sort(taskList,new Comparator<Task>(){ //here is one NPE
                  @Override
                  public int compare(Item t1,Item t2){
                      if(t1==null || t2==null){
                        return 0;
                      }
                      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-16
        • 2015-07-25
        • 2013-08-01
        • 1970-01-01
        • 2016-07-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多