public void showAll(){//to string method
    for (int i=0;i<phoneBook.length;i++){//index is going till 2 where it
        System.out.println(phoneBook[i].toString());
    }
    //the above code iterates for 20 times because the length of the array is 20.
    public phoneBookUnsoterdOptimizedArray( )
    {
        next = 0;
        size = 20;//this initializes the array to size 20.
        phoneBook = new PhoneBook[size];
    }//end of constructor


我尝试了if语句检查null,但这不起作用。

输出量

Phone Number: 4695866399
lastName: Ayoub
First Name: Rehan
address: 9323 Amberton Pkwy
Exception in thread "main" Phone Number: 971506236329
lastName: Ayoub
First Name: Syed
address: 14th Street Nyadat
java.lang.NullPointerException
    at phonebook.phoneBookUnsoterdOptimizedArray.showAll(phoneBookUnsoterdOptimizedArray.java:74)
    at phonebook.FA2015PROJECT_Ayoub.main(FA2015PROJECT_Ayoub.java:35)

最佳答案

您可以显式检查null

for (int i = 0; i < phoneBook.length; i++) {
    if (phoneBook[i] == null) {
        break;
    }
    System.out.println(phoneBook[i].toString());
 }

09-25 21:47