简体   繁体   English

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

[英]How to define a multidimensional array in Java using curly braces?

I don't understand the behaviour of Java about arrays. 我不了解Java关于数组的行为。 It forbids to define an array in one case but allows the same definition in another. 它禁止在一种情况下定义数组,但在另一种情况下允许相同的定义。

The example from tutorial: 教程中的示例:

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

My example: 我的例子:

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;
      }
    }

The mistakes thrown by NetBeans are: NetBeans引发的错误是:

illegal start of expression, 非法开始表达,

";" “;” expected , 预期的

not a statement . 不是声明

And also it doesn't recognize arguments email , name , pass in the definition of the users array. 并且它不识别参数emailnamepass users数组的定义。 But recognizes them when I define u array. 但是当我定义u数组时识别它们。

What is the difference between these two definitions? 这两个定义有什么区别? Why the one works but the another one defined the same way doesn't? 为什么一个工作但另一个定义相同的方式不?

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

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

You can use this syntax: 您可以使用以下语法:

String[][] u = {{email, name, pass}, {"one@one.com", "jack sparrow", "12345"}};

Only when you're declaring the matrix for the first time. 只有当你第一次声明矩阵时。 It won't work for assigning values to a String[][] variable after you've declared it elsewhere, that's why users = ... fails. 在将其声明到其他地方 ,它将无法为String[][]变量赋值,这就是users = ...失败的原因。 For assigning values to an already-declared String[][] (or a matrix of any other type for that matter), use 要将值分配给已声明的String[][] (或任何其他类型的矩阵),请使用

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

The first case is an initialization statement, while the second is only an assignment. 第一种情况是初始化语句,而第二种情况只是一种赋值。 That kind of filling arrays is only supported when defining a new array. 只有在定义新数组时才支持这种填充数组。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM