2015-05-24 98 views
2

我很困惑我的陣列是如何形成的。這是寫入數組的內容。有人可以解釋這個數組是怎麼回事?

public class TestProgram { 

public static final Room[] rooms = new Room[] 
{ 
    new Room ("GARDEN0001", "NorthWest Garden View", 45.00), 
    new Room ("GARDEN0002", "SouthEast Garden View", 65.0), 
    new Room ("GARDEN0003", "North Garden View", 35), 
    new Room ("GARDEN0004", "South Garden View", 52), 
    new Room ("GARDEN0005", "West Garden View", 35), 
    new Room ("GARDEN0006", "East Garden View", 35) 
}; 

,我認爲數據來源於此類:

public class Room { 
    public Room(String roomId, String description, double dailyRate){ 
     this.roomId = roomId; 
     this.description = description; 
     this.dailyRate = dailyRate; 
     this.status = 'A'; 
    } 

我們該從另一個類或東西構造函數聲明數組的方式嗎?我很困惑,但它的作品。

有人可以向我解釋爲什麼它寫爲Room[] rooms = new Room[]

+0

可能重複http://stackoverflow.com/questions/1200621/declare-array-in-java –

+0

我真的不知道你是什麼困惑。你能否給我們比較一下你認爲數組通常是如何「形成」的? – digawp

+0

你可以寫得更簡單'Room [] rooms = {new Room(...),...};'。 – saka1029

回答

1

這是數組的內聯初始化。

「通常情況下」你會聲明一個特定長度的數組,然後初始化它或放到相關數據中(可能在循環中)。但是,它可以在一個行完成,喜歡這裏 - 一個簡單的例子是:

int[] numbers = new int[]{2, 3, 5}; 

在這裏,我們有相同的情況下,只是「數字」是房對象(每個創建的,在這裏初始化),而不是int數字。請注意,數組是最終的 - 一旦你給它分配了一些東西,就是它(你可以改變數組中的數據,但不是它的長度 - 或者改變它來指向另一個數組)。如果你的數據是最終的 - 一次分配更清晰。

最後,它是靜態的 - 你不能在構造函數中完成它,除非你確定它是NULL(它第一次可以工作,但之後的其他所有工作都會失敗,因爲你會試圖重新分配一個共同的final目的)。

總而言之,內聯聲明和最終靜態數組的初始化。 :-)

+0

我已編輯你的答案,新號碼[]不會編譯 – Iamsomeone

+0

哦,謝謝 - 沒有抓住那個:-) – st2rseeker

2

其分解:

Room[] rooms 

聲明一個靜態字段(類變量)與名稱rooms和類型Room[]Room對象數組。

= new Room[] {new Room...}; 

初始化與Room對象陣列,並且還定義了陣列的尺寸(其在java中不能改變)。

0

在這裏您聲明並初始化房間的array。看 -

Room rooms[] // declaration of 'Room' array  

之後 -

new Room[] 
{ 
    new Room ("GARDEN0001", "NorthWest Garden View", 45.00), 
    new Room ("GARDEN0002", "SouthEast Garden View", 65.0), 
    new Room ("GARDEN0003", "North Garden View", 35), 
    new Room ("GARDEN0004", "South Garden View", 52), 
    new Room ("GARDEN0005", "West Garden View", 35), 
    new Room ("GARDEN0006", "East Garden View", 35) 
}; //initialization of the array. 

現在這裏你Room與您這裏提到的數組元素創建並獲得6.你數組聲明的大小和初始化實際上是等同於以下代碼片段 -

int[] intArray = new int[]{11,222,333, 444};  

而且是你的數據放入數組rooms來通過房類的構造函數。並看看Room創建的對象 - new Room ("GARDEN0001", "NorthWest Garden View", 45.00)將在room[0]中找到。同樣 -

room[1] <-- new Room ("GARDEN0002", "SouthEast Garden View", 65.0) 
room[2] <-- new Room ("GARDEN0003", "North Garden View", 35) 
room[3] <-- new Room ("GARDEN0004", "South Garden View", 52) 
room[4] <-- new Room ("GARDEN0005", "West Garden View", 35) 
room[5] <-- new Room ("GARDEN0006", "East Garden View", 35)