2014-05-18 44 views
5

請別人幫我理解這個數組的創建方式。無法理解數組聲明int [] it2 = new int [] [] {{1}} [0];

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

it2是一維數組,在右邊我們有奇怪的初始化類型。代碼編譯得很好,但我能夠理解它是如何工作的。

+11

它通常由程序員誰不想結交新朋友。 – Maroun

+0

該表達式是一個有效的java表達式。所以我想這是關於java並添加了java標籤。糾正我,如果我錯了。 – yankee

回答

11

打破錶達的部分,以便更好地理解它們:

int[] first = new int[]{1}; // create a new array with one element (the element is the number one) 
int[][] second = new int[][]{first}; // create an array of the arrays. The only element of the outer array is the array created in the previous step. 
int[] third = second[0]; // retrieve the first (and only) element of the array of array `second`. This is the same again as `first`. 

現在,我們將再次合併這些表達式。首先,我們合併firstsecond

int[][] second = new int[][]{new int[]{1}}; 
int[] third = second[0]; 

OK,沒什麼大不了的。然而,表達式second可能是短暫的。以下是等價物:

int[][] second = new int[][]{{1}}; 
int[] third = second[0]; 

現在我們合併第二和第三。我們可以直接寫:

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

而我們在那裏。

相關問題