Sakit Atakishiyev
Sakit Atakishiyev

Reputation: 29

How do I initialize a two-dimensional array?

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
    }

How can I initialize p[].x and p[][].x?

Upvotes: 2

Views: 11033

Answers (4)

Vala
Vala

Reputation: 5674

Think of it this way; when you do new point[5] (you should follow coding standards and name your classes with an upper case first letter btw.), you get an array with every element being the default value for that type (in this case null). The array is initialised, but if you want individual elements of the array to be initialised, you have to do that as well, either in the initial line like this:

point[] p1 = new point[] { new point(), new point() };

(The above method will create an array with each element already initialised of the minimum size that will accommodate those elements - in this case 2.)

Or by looping through the array and adding the points manually:

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

Both these concepts can be extended to multi-dimensional arrays:

point[] p2 = new point[][] {
    new point[] { new point(), new point() }
    new point[] { new point(), new point() }
};

Or

point[] p2 = new point[5][5];
for (int i = 0; i < p2.length; i++) {
    for (int j = 0; j < p2[i].length; j++) {
        p2[i][j] = new point();
    }
}

Upvotes: 2

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41240

 point p = new point();

It is the point object.

point[] p1 = new point[5];

This point object is an 1D array. It holds point object references. You should create a point object and keep into the array like -

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

p1[0].x = 1;

And for a 2D array -

point[][] p2 = new point[5][5];

for (int i = 0; i < 5; i++){
  for (int j = 0; j < 5; j++)
      p1[i][j] = new point();
}
p[0][0].x = 5;

Upvotes: 0

Matzi
Matzi

Reputation: 13925

You need to manually initialize the whole array and all levels if multi-leveled:

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

Upvotes: 5

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

When you construct an array of objects, the array itself is constructed, but the individual elements are initialized to null. So, assuming Point() is the constructor you want,

Point[] p1 = new Point[5];
for (int i = 0; i < p1.length; ++i) {
  p1[i] = new Point();
}

Upvotes: 0

Related Questions