Вопрос

I do not understand why this code throws a null pointer exception because I thought line 3 sets the value of sampleArray[0][0]) to 1.

int arrSize = 100;
String[][] sampleArray = new String[arrSize][];
sampleArray[0][0]="1";
System.out.println(sampleArray[0][0]);

Any help?

Это было полезно?

Решение

sampleArray[0] has not been initialized as an array. You initialized the first dimension of the array, but not the second one

You would need to do something like sampleArray[0] = new String[size]

The initializer String[][] sampleArray = new String[arrSize][] works because you are creating an array that has references to other arrays. Each one of those other arrays can have a different size which you can set as you wish. What I mean is that the following would be perfectly legal:

sampleArray[0] = new String[10]; sampleArray[1] = new String[5]; System.out.println(sampleArray[0][9]); System.out.println(sampleArray[1][4]);

Другие советы

You can't set only the first dimension's size of a 2d array. Because it's an array of arrays, so you can't get back an array of not instantiated arrays.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top