簡體   English   中英

Java Object Null檢查方法

[英]Java Object Null Check for method

我需要在這個公式[i]中創建一個空檢查,我不完全確定如何解決這個問題,因為我不太熟悉null檢查和編程方面的新功能。 任何和所有的幫助非常感謝!

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 要檢查每個元素是否為空,請使用

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;
}

如果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;
}

你可以決定輸入空輸入值是否正確(不正確,但......)。

您只需使用== (或!= )運算符將對象與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;
}

在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<Book> 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<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();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM