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

I do not understand Java behavior about arrays. It prohibits defining an array in one case, but allows the same definition in another.

Example from the 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 errors caused by NetBeans are as follows:

illegal launch of an expression,

";" expected,

not a statement.

And also it does not recognize the arguments email , name , pass in the definition of the users array. But it recognizes them when I define an u array.

What is the difference between these two definitions? Why does one work and the other, defined in the same way, does not work?

+6
source share
4 answers

You need to add new String[][] before array aggregation:

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

You can use this syntax:

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

Only when you first declare a matrix. It will not work to assign the values ​​of the variable String[][] after you declare it elsewhere, so users = ... does not work. To assign values ​​to an already declared String[][] (or any other type of matrix, for that matter), use

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

The first case is the initialization operator, and the second is only the destination. Fill arrays of this kind are only supported when defining a new array.

+2
source

To reassign the matrix you should use new :

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

Source: https://habr.com/ru/post/916382/


All Articles