Java Object Null检查方法

我需要在这个公式[i]中创建一个空检查,我不完全确定如何解决这个问题,因为我不太熟悉null检查和编程方面的新function。 任何和所有的帮助非常感谢!

public static double calculateInventoryTotal(Book[] books) { double total = 0; for (int i = 0; i < books.length; i++) { total += books[i].getPrice(); } return total; } 

首先你应该检查books本身是否为空,然后检查books[i] != null

 if(books==null) throw new IllegalArgumentException(); for (int i = 0; i < books.length; i++){ if(books[i] != null){ total += books[i].getPrice(); } } 

您可以向方法添加保护条件以确保books不为null,然后在迭代数组时检查null:

 public static double calculateInventoryTotal(Book[] books) { if(books == null){ throw new IllegalArgumentException("Books cannot be null"); } double total = 0; for (int i = 0; i < books.length; i++) { if(books[i] != null){ total += books[i].getPrice(); } } return total; } 

如果您使用的是Java 7,您可以使用Objects.requireNotNull(object[, optionalMessage]); – 检查参数是否为null 。 要检查每个元素是否为null,请使用

 if(null != books[i]){/*do stuff*/} 

例:

 public static double calculateInventoryTotal(Book[] books){ Objects.requireNotNull(books, "Books must not be null"); double total = 0; for (int i = 0; i < books.length; i++){ if(null != book[i]){ total += books[i].getPrice(); } } return total; } 

您只需使用== (或!= )运算符将对象与null进行比较。 例如:

 public static double calculateInventoryTotal(Book[] books) { // First null check - the entire array if (books == null) { return 0; } double total = 0; for (int i = 0; i < books.length; i++) { // second null check - each individual element if (books[i] != null) { total += books[i].getPrice(); } } return total; } 

如果Books的数组为null,则返回零,因为它看起来方法计算所有提供的书籍的总价格 – 如果没有提供Book,则零是正确的值:

 public static double calculateInventoryTotal(Book[] books) { if(books == null) return 0; double total = 0; for (int i = 0; i < books.length; i++) { total += books[i].getPrice(); } return total; } 

你可以决定输入空输入值是否正确(不正确,但......)。

在for循环中,只需添加以下行:

 if(books[i] != null) { total += books[i].getPrice(); } 

这个问题比较老了。 此时,提问者可能已经变成了一位经验丰富的Java开发人员。 但是我想在这里添加一些有助于初学者的意见。

对于JDK 7用户,请在此处使用

 Objects.requireNotNull(object[, optionalMessage]); 

不安全 如果此函数找到null对象并且是RunTimeException ,则抛出NullPointerException

这将终止整个计划!! 所以最好使用==!=检查null

另外,使用List而不是Array 。 尽管访问速度相同,但使用Collections over Array具有一些优势,例如,如果您决定稍后更改底层实现,则可以灵活地执行此操作。 例如,如果需要同步访问,则可以将实现更改为Vector而无需重写所有代码。

 public static double calculateInventoryTotal(List books) { if (books == null || books.isEmpty()) { return 0; } double total = 0; for (Book book : books) { if (book != null) { total += book.getPrice(); } } return total; } 

另外,我想upvote @ 1ac0的答案。 在写作时我们也应该理解并考虑方法的目的。 调用方法可以根据被调用方法的返回数据进一步实现逻辑。

此外,如果您使用JDK 8进行编码,它还引入了一种新方法来处理空检查并保护代码免受NullPointerException 。 它定义了一个名为Optional的新类。 详细了解一下这个

最后,请原谅我糟糕的英语。

 public static double calculateInventoryTotal(Book[] arrayBooks) { final AtomicReference total = new AtomicReference<>(BigDecimal.ZERO); Optional.ofNullable(arrayBooks).map(Arrays::asList).ifPresent(books -> books.forEach(book -> total.accumulateAndGet(book.getPrice(), BigDecimal::add))); return total.get().doubleValue(); }