Java 对象空检查方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21664478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Object Null Check for method
提问by CoShark
I need to create a null check in this formula for the books[i] and I am not entirely sure how to go about this as I am not greatly familiar with null checks and very new at programming. Any and all help is much appreciated!
我需要在此公式中为书籍 [i] 创建一个空检查,但我不完全确定如何进行此操作,因为我对空检查不太熟悉,而且对编程非常陌生。非常感谢任何和所有帮助!
public static double calculateInventoryTotal(Book[] books)
{
double total = 0;
for (int i = 0; i < books.length; i++)
{
total += books[i].getPrice();
}
return total;
}
采纳答案by Kuba Spatny
First you should check if books
itself isn't null, then simply check whether books[i] != null
:
首先你应该检查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();
}
}
回答by Svetlin Zarev
If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]);
- to check if the parameter is null
. To check if each element is not null just use
如果您使用的是 Java 7 您可以使用Objects.requireNotNull(object[, optionalMessage]);
- 检查参数是否为null
. 要检查每个元素是否不为空,只需使用
if(null != books[i]){/*do stuff*/}
Example:
例子:
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;
}
回答by 1ac0
If array of Books is null, return zero as it looks that method count total price of all Books provided - if no Book is provided, zero is correct value:
如果 Books 数组为 null,则返回零,因为它看起来该方法会计算提供的所有 Books 的总价 - 如果未提供 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;
}
It's upon to you to decide if it's correct that you can input null input value (shoul not be correct, but...).
由您来决定您可以输入空输入值是否正确(应该不正确,但是......)。
回答by John
Inside your for-loop, just add the following line:
在 for 循环中,只需添加以下行:
if(books[i] != null) {
total += books[i].getPrice();
}
回答by Kevin Bowersox
You can add a guard condition to the method to ensure books
is not null and then check for null when iterating the array:
您可以向方法添加保护条件以确保books
不为空,然后在迭代数组时检查是否为空:
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;
}
回答by Mureinik
You simply compare your object to null
using the ==
(or !=
) operator. E.g.:
您只需将您的对象与null
使用==
(or !=
) 运算符进行比较。例如:
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;
}
回答by rookie4evr
This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.
这个问题比较老了。这个时候提问者可能已经变成了一个有经验的 Java 开发人员。但是我想在这里添加一些有助于初学者的意见。
For JDK 7 users, Here using
对于 JDK 7 用户,这里使用
Objects.requireNotNull(object[, optionalMessage]);
is not safe. This function throws NullPointerException
if it finds null
object and which is a RunTimeException
.
不安全。NullPointerException
如果此函数找到null
对象并且哪个是RunTimeException
.
That will terminate the whole program!!. So better check null
using ==
or !=
.
这将终止整个程序!!所以最好null
使用==
或检查!=
。
Also, use List
instead of Array
. Although access speed is same, yet using Collections
over Array
has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector
without rewriting all your code.
另外,使用List
代替Array
. 虽然访问速度相同,但使用Collections
overArray
有一些优点,例如如果您决定稍后更改底层实现,您可以灵活地进行。例如,如果您需要同步访问,您可以将实现更改为 a,Vector
而无需重写所有代码。
public static double calculateInventoryTotal(List<Book> books) {
if (books == null || books.isEmpty()) {
return 0;
}
double total = 0;
for (Book book : books) {
if (book != null) {
total += book.getPrice();
}
}
return total;
}
Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.
另外,我想支持@1ac0 的答案。我们在写作时也应该理解和考虑方法的目的。调用方法可以根据被调用方法的返回数据进一步实现逻辑。
Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException
. It defined a new class called Optional
. Have a look at this for detail
此外,如果您使用 JDK 8 进行编码,它引入了一种新方法来处理空检查并保护代码免受NullPointerException
. 它定义了一个名为Optional
. 看看这个细节
Finally, Pardon my bad English.
最后,请原谅我的英语不好。
回答by Marco Tulio Avila Cerón
public static double calculateInventoryTotal(Book[] arrayBooks) {
final AtomicReference<BigDecimal> 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();
}