如何初始化二维数组?

Sak*_*yev 2 java arrays initialization

public class example
{
    static class point
    {
        int x;
        int y;
    }

    static void main(String args[])
    {
        point p = new point();
        point[] p1 = new point[5];
        point[][] p2 = new point[5][5];

        p.x = 5; //No problem
        p[0].x = 5; //When I run the program, it gives error:java.lang.NullPointerException
        p[0][0].x = 5; //When I run the program, it gives error:java.lang.NullPointerException
    }
Run Code Online (Sandbox Code Playgroud)

如何初始化p [].x和p [] [].x?

Mat*_*tzi 5

您需要手动初始化整个阵列和所有级别(如果多级):

point[] p1 = new point[5];
// Now the whole array contains only null elements

for (int i = 0; i < 5; i++)
  p1[i] = new point();

p1[0].x = 1; // Will be okay
Run Code Online (Sandbox Code Playgroud)