如何使用花括号在Java中定义多维数组?

时间:2012-05-22 18:10:33

标签: java arrays multidimensional-array

我不了解Java关于数组的行为。它禁止在一种情况下定义一个数组,但在另一种情况下允许相同的定义。

教程中的示例:

String[][] names = {
        {"Mr. ", "Mrs. ", "Ms. "},
        {"Smith", "Jones"}
    };
System.out.println(names[0][0] + names[1][0]);    // the output is "Mr. Smith";

我的例子:

public class User {
   private static String[][] users;
   private static int UC = 0;

   public void addUser (String email, String name, String pass) {
      int i = 0;

      // Here, when I define an array this way, it has no errors in NetBeans
      String[][] u = { {email, name, pass}, {"one@one.com", "jack sparrow", "12345"} };

      // But when I try to define like this, using static variable users declared above, NetBeans throws errors
      if (users == null) {
         users = { { email, name, pass }, {"one", "two", "three"} };    // NetBeans even doesn't recognize arguments 'email', 'name', 'pass' here. Why?

         // only this way works
         users = new String[3][3];
         users[i][i] = email;
         users[i][i+1] = name;
         users[i][i+2] = pass;
         UC = UC + 1;
      }
    }

NetBeans引发的错误是:

非法开始表达,

“;”预期

不是声明

此外,它还无法识别email数组定义中的参数namepassusers。但是在我定义u数组时会识别它们。

这两个定义有什么区别?为什么一个有效但另一个定义方式不同?

4 个答案:

答案 0 :(得分:11)

您需要在数组聚合之前添加new String[][]

users = new String[][] { { email, name, pass }, {"one", "two", "three"} };

答案 1 :(得分:5)

您可以使用以下语法:

String[][] u = {{email, name, pass}, {"one@one.com", "jack sparrow", "12345"}};
第一次声明矩阵时,

。 在之后在其他地方声明后,它将无法为String[][]变量分配值,这就是users = ...失败的原因。要将值分配给已声明的String[][](或任何其他类型的矩阵),请使用

users = new String[][] { { email, name, pass }, {"one", "two", "three"} };

答案 2 :(得分:2)

第一种情况是初始化语句,而第二种情况只是一种赋值。只有在定义新数组时才支持这种填充数组。

答案 3 :(得分:2)

要重新分配矩阵,您必须使用new

users = new String[][] {{email, name, pass }, {"one", "two", "three"}};