簡體   English   中英

如何初始化二維數組?

[英]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
    }

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

您需要手動初始化整個數組以及所有級別(如果是多層的):

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

這樣想吧; 當你做new point[5] (你應該遵循編碼標准並用大寫的第一個字母btw命名你的類。),你得到一個數組, 每個元素都是該類型的默認值 (在這種情況下為null)。 數組已初始化,但如果您希望初始化數組的各個元素,您也必須這樣做,或者在初始行中執行此操作,如下所示:

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

(上面的方法將創建一個數組,每個元素已經初始化了最小尺寸,將容納這些元素 - 在這種情況下為2.)

或者通過循環遍歷數組並手動添加點:

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

這兩個概念都可以擴展到多維數組:

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

要么

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();

它是point對象。

point[] p1 = new point[5];

point對象是一維數組。 它保存point對象引用。 您應該創建一個point對象,並像這樣保留在數組中:

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

p1[0].x = 1;

對於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;

構造對象數組時,將構造數組本身,但是將各個元素初始化為null。 因此,假設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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM