如果list在这种情况下为空,我怎样才能避免java中的空指针异常?

时间:2013-09-13 08:45:52

标签: java collections nullpointerexception

public static void selectEMployee() {
   if (list1.isEmpty()) {
         System.out.println("The list is empty");
   }else {
         System.out.println("The list of employees are");
         for (Employee emp : list1) {
           System.out.println("Name::" + emp.getName() + "\t EmpId::"
                            + emp.getEmpid() + "\t Address::" + emp.getAddress()
                            + "\tphone::" + emp.getPhone());
         }       
    }
}

当列表为空时我想显示“列表为空”但它会抛出异常吗?

5 个答案:

答案 0 :(得分:11)

list对象与list类型的变量之间存在差异,但尚未将其指定为list的引用。

即。检查list1 == null。如果 null,请不要测试空虚,因为您将获得NullPointerException

将它们组合在一起,写下if (list1 == null || list1.isEmpty()){。这是安全的,因为Java从左到右评估if语句,一旦有明确的答案就停止。

答案 1 :(得分:2)

应用这个小修补程序,它会起作用:

if (list1 == null || list1.isEmpty()) {
    System.out.println("The list is empty");
}

答案 2 :(得分:1)

public static void selectEMployee() {
            if (list1.isEmpty() || list1==null) //changes made here{
               System.out.println("The list is empty");
            }// this is not allowed here
            } else {
 System.out.println("The list of employees are");
                for (Employee emp : list1) {
                    System.out.println("Name::" + emp.getName() + "\t EmpId::"
                            + emp.getEmpid() + "\t Address::" + emp.getAddress()
                            + "\tphone::" + emp.getPhone());
                }


        }

你正在关闭方法之前if if for loop关闭

答案 3 :(得分:1)

看起来你的list1-var没有被初始化。你应该这样检查:

if(list1 == null || list1.isEmpty())

答案 4 :(得分:1)

尝试一次

public static void selectEMployee() {

  if (list1!=null && !list1.isEmpty()) {
      System.out.println("The list of employees are");

      for (Employee emp : list1) {
           System.out.println("Name::" + emp.getName() + "\t EmpId::"
            + emp.getEmpid() + "\t Address::" + emp.getAddress()
            + "\tphone::" + emp.getPhone());
      }

  } else {
      System.out.println("The list is empty");
  }
}