2012-05-22 31 views
6

我不明白Java关于数组的行为。它禁止在一种情况下定义数组,但允许在另一种情况下使用相同的定义。如何使用大括号在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}, {"[email protected]", "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的抛出的错误是:

表达的非法启动,

“ ;”预计,

不是一个声明

并且它也不识别users阵列的定义中的参数email,name,pass。但是当我定义u数组时,它们会识别它们。

这两个定义有什么区别?为什么这个工作正常,但另一个定义的方式不一样?

回答

11

您需要的阵列聚集前添加new String[][]

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

但是我有已经完成了。在“public class User {”的行下面是“private static String [] [] users' – Green

+2

@Green'这行代码当你将初始化和声明结合起来时,隐含了'new String [] []'部分;当你在一个地方声明一个字段或变量,但在不同的地方初始化它时,你需要明确地提供你在数组聚合之前创建的对象的类型。 – dasblinkenlight

2

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

5

你可以使用这个语法:

String[][] u = {{email, name, pass}, {"[email protected]", "jack sparrow", "12345"}}; 

只有当你宣布首次矩阵。如果在其他地方声明,则变量的值不会起作用,因此users = ...失败。对于一个已经宣布String[][](或任何其他类型为此事的矩阵)分配值,使用

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

重新分配必须使用new矩阵:

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