68

I have a problem understanding this piece of code:

int[] it = new int[][]{{1}}[0];

Why is it compileable, and how can I understand such a declaration?

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
user2654250
  • 683
  • 5
  • 9
  • 17
    Off-topic, but I'm surprised this question is so well-received. It seems most questions these days that are less than four sentences long and/or are about asking "what does this do" get downvoted to oblivion =P. – theGreenCabbage Dec 04 '13 at 14:57
  • @theGreenCabbage: I think the enthusiasm for this question is a little overrated, but I can see how this would be a confusing line of code for someone new to Java. – Jeroen Vannevel Dec 04 '13 at 14:59
  • @JeroenVannevel Oh it was confusing to me too when I first saw it, so I guess that does mean something! – theGreenCabbage Dec 04 '13 at 15:00
  • 6
    @theGreenCabbage sufficiently interesting questions **are** above the law – Richard Tingle Dec 04 '13 at 15:21
  • 2
    @theGreenCabbage give programmers a fitting puzzle and they'll drool. ;) (BTW this question is now featured on all SE sites) – Shadow The GPT Wizard Dec 04 '13 at 15:32
  • Well, I certainly am interested in it, but I'm wondering why such a declaration would be used. It's essentially a really confusing way of storing a single variable into a mult-dimen. What could this be used for? – theGreenCabbage Dec 04 '13 at 15:38
  • 25
    I really hope you found that in some book of "Java Tricks" or something, and it's not some actual production code someone wrote. – Shivan Dragon Dec 04 '13 at 15:58
  • 3
    This could be a simplified example of the concrete situation. For example he might make a 2x2 field like this and get the first row: `int[] it = new int[][]{{1, 2}, {3, 4}}[0];` It's not very common, but it's not the most unreadable code either. – Jeroen Vannevel Dec 04 '13 at 16:59
  • You assign the value of the first element "[0]" of two dimensional array "[][]" which first element is an array "{{}}" with one element in it which is an array "{1}" with one element "1" to a newly declared variable "int[]" named "it". In the result the "it" is a one element array: {1}; – luke1985 Dec 04 '13 at 17:17
  • 1
    wouldn't `int[] it = new int[] {1};` be more concise? – Jodrell Dec 04 '13 at 17:52
  • How can this question not be a duplicate more than five years after Stack Overflow started and with approximately 528571 Java questions? We need a human search in this case - Google is not much help. A starting point may be [an answer to *Initialising a multidimensional array in Java*](http://stackoverflow.com/questions/1067073/initialising-a-multidimensional-array-in-java/1067729#1067729) which has a similar contruct. – Peter Mortensen Dec 04 '13 at 19:53
  • 1
    @user2654250 Be advised that you can accept an answer if it answers your question. – Adam Arold Dec 04 '13 at 20:35
  • @theGreenCabbage I think the reason is the esoteric look of the code which actually compiles. – Adam Arold Dec 04 '13 at 22:31
  • Wow, I assumed at first glance it was something new from C++11. – Chris Dec 05 '13 at 04:43
  • 1
    @Chris Consider this code then: `private List list = new ArrayList(){{ add("Something"); }};`. This is almost as esoteric like the one in the question. The first brace creates an anonymous instance of `ArrayList` while the second one is an instance initializer block (that's why you can use `add` without a reference). – Adam Arold Dec 05 '13 at 11:09
  • 1
    @AdamArold You can't fool me with that one, I recognize it from using JMock. :) Don't think I've ever used it in any other context apart from JMock, tho. – Chris Dec 06 '13 at 03:22
  • I use it elsewhere: in Mockito HAHA. – Adam Arold Dec 06 '13 at 12:03

6 Answers6

103

What you are doing here is:

  1. Declaring a new variable int[] it (which is a one-dimensional array)
  2. Assigning its value from the first element [0]
  3. of the two-dimensional array new int[][]
  4. which is initialized to be {{1}}

So you create a two-dimensional array which you initialize to contain an array which contains 1 and at the same time you take the first element of the outer array (which is a one-dimensional array containing 1) and assign it to your variable.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
  • Cool. Learned something new today. So technically there's no need for this multidimensional array? The `{{1}}` is simply placing a single `1` into a multi-dimensional. What could/would be the use for such a declaration? – theGreenCabbage Dec 04 '13 at 15:01
  • I don't see any valid purpose for it in this context. It can be useful if you need to supply parameters in this format for some legacy library though. – Adam Arold Dec 04 '13 at 15:27
  • 1
    Very nice explanation, "as simple as possible, as complex as necessary" :) – acostache Dec 10 '13 at 21:16
30
int[] it = new int[][]{{1}}[0];

Let's break this one down into each stage, and what it means.

new int[][] 

This is a new multidimensional array.

{{1}} 

This is a multidimensional array literal. It makes an array that looks like this:

[0] = [1]
[1] = []
[2] = []
...
[N] = []

So take note, each element inside this array is itself an array. Then you've specified that your variable it is equal to the first array in the multidimensional array, so it equates directly to:

int[] it = new int[] {1};
christopher
  • 26,815
  • 5
  • 55
  • 89
  • 4
    At the time of posting, I didn't really see any other answers that broke down the statement like this. – christopher Dec 04 '13 at 15:25
  • I like these types of explanations. I definitely emulate this type of answer style when I try to explain something that breaks down individual elements that are properly structured. Sometimes I learn something on the mean time that I break it down! I also make use of it when I try to debug my own code. – theGreenCabbage Dec 05 '13 at 03:23
  • Nice breakdown, but you mistyped the initializer: {{1}}, not {{0}}. – Justsalt Dec 11 '13 at 16:31
  • I find the part "_`{{1}}` […] makes an array that looks like this: […] `[10] = []`_" is misleading: There is no such thing as `[10]` because the outer array is only of size 1, so the only element is at index 0 (and contains another array of size 1 containing the integer 1, as you stated correctly). While I'm already at nitpicking, I think you missed to update the very last line (should be `{1}`, not `{0}`). And one last note, just for fun: You can even shorten the line to just `int[] it = {1};` (this only works while declaring an array variable, in all other cases you'll need `new int[]{…}`). – siegi Dec 12 '13 at 08:19
  • While I appreciate you taking the time to read my answer, only the `{1}` criticism is valid. With the `0-10` I was trying to illustrate the point that the rest of it is empty.. which I did. Cheers. – christopher Dec 12 '13 at 09:07
9

The new int[][]{{1}} allocates a new 1x1 2D array. The (only) element is set to 1.

The [0] returns a reference to the first (and the only) row, which is of type int[].

The int[] it = ... declares a variable and initializes it with the above reference.

The end result is equivalent to int[] it = new int[]{1}.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
6

Essentially, you are creating an anonymous two-dimensional array (new int[][]{{1}}) and then taking the first element of that two-dimensional array ({1}) and assigning it to the variable it.

Let's go step-by-step, because this actually is kind of confusing.

new int[][]{{1}}: This creates a two-dimensional array which has only one element: an array, which contains one array, which contains one int (the number 1). Because it's not assigned to a variable anywhere and won't be accessible past this statement, we call it "anonymous", and it has the smallest scope possible.

[0]: This accesses the first element of the anonymous two-dimensional array we created above. The first element is a one-dimensional array containing 1 (i.e., {1}).

int[] it =: Finally, here we take that retrieved one-dimensional array and store it in our variable.

As a side note, there's absolutely no reason to do it this way, and it seems like just a very interesting Java puzzle.

asteri
  • 11,402
  • 13
  • 60
  • 84
6

I will try to break it down

new int[][] // an array of arrays (or 2-dimensional array)
{1} // an array instance with a single element: 1
{{1}} // an array instance with a single element: above array instance
[0] // the first element of an array

So it is roughly equivalent to the following code:

int[] inner = new int[1]; // an empty array with length 1
inner[0] = 1;
int[][] outer = new int[1][];
outer[0] = inner;

int[] it = outer[0];
Max Fichtelmann
  • 3,366
  • 1
  • 22
  • 27
5
int[] it = new int[][]{{1}}[0];

The integer array it gets assigned the following:

new int[][] // A new 2D array is created
{{1}} // This is an initializer. The first array in the first array gets an array of 1 item: '1'
[0] // Take the first array from the 2D array
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170