This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                4年前关闭。
            
        

public class TestDogs {

    public static void main(String [] args) {

        Dog [][] theDogs = new Dog[3][];
        System.out.println(theDogs[2][0].toString());
    }
}

class Dog{ }

最佳答案

theDogs[2]数组为空,因为您没有初始化它。即使您初始化了它,theDogs[2][0]仍然为空,因此在其上调用toString仍然会抛出NullPointerException

示例如何初始化数组和Dog实例:

Dog [][] theDogs = new Dog[3][];
theDogs[2] = new Dog[7]; // initialize the 3rd row of theDogs 2D array
theDogs[2][0] = new Dog (); // initialize the Dog instance at the 1st column of the 3rd row
System.out.println(theDogs[2][0].toString()); // now you can execute methods of theDogs[2][0]

09-27 23:44