[英]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? 如何初始化p []。x和p [] []。x?
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
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). 当你做new point[5]
(你应该遵循编码标准并用大写的第一个字母btw命名你的类。),你得到一个数组, 每个元素都是该类型的默认值 (在这种情况下为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.) (上面的方法将创建一个数组,每个元素已经初始化了最小尺寸,将容纳这些元素 - 在这种情况下为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();
}
}
point p = new point();
It is the point
object. 它是point
对象。
point[] p1 = new point[5];
This point
object is an 1D array. 该point
对象是一维数组。 It holds point
object references. 它保存point
对象引用。 You should create a point
object and keep into the array like - 您应该创建一个point
对象,并像这样保留在数组中:
for (int i = 0; i < 5; i++)
p1[i] = new point();
p1[0].x = 1;
And for a 2D array - 对于2D阵列-
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;
When you construct an array of objects, the array itself is constructed, but the individual elements are initialized to null. 构造对象数组时,将构造数组本身,但是将各个元素初始化为null。 So, assuming Point()
is the constructor you want, 因此,假设Point()
是您想要的构造函数,
Point[] p1 = new Point[5];
for (int i = 0; i < p1.length; ++i) {
p1[i] = new Point();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.