2012-09-07 331 views
-3

我有一個類叫ElementInfo創建對象的數組

public class ElementInfo { 

    public String name; 
    public String symbol; 
    public double mass; 

} 

然後我試圖創建的ElementInfo這樣一個數組:

ElementInfo e[] = new ElementInfo[2]; 

e[0].symbol = "H"; 
e[0].name = "Hydrogen"; 
e[0].mass = 1.008; 

//... 

不要告訴我,我得叫new爲每類的實例!

我可以這樣做:

ElementInfo e[] = new ElementInfo[100]; 
for(ElementInfo element: e){ 
    e = new ElementInfo(); 
} 
+0

那麼,你想怎麼做?你有沒有其他想法? – kosa

+1

小心你稱之爲類和對象。你已經創建了一個具有特定類的對象數組。 –

+0

我打算說一個類對象數組 – nick

回答

3

你必須爲類的每一個元素調用new。

public class ElementInfo { 

    private String name; 
    private String symbol; 
    private double mass; 

    public String get_name() { return name; } 
    public String get_symbol() { return symbol; } 
    public double get_mass() { return mass; } 

    public ElementInfo(name, symbol, mass) { 
     this.name = name; 
     this.symbol = symbol; 
     this.mass = mass; 
    } 
} 

然後,像這樣創建它們:

e[0] = new ElementInfo("H", "Hydrogen", 1.008); 
+0

構造函數強制我爲每個元素輸入名稱,符號和質量。我希望班級的行爲像一個結構 – nick

+0

,這也意味着您將對象保留在分配給它的不一致狀態中。對於未來的最佳實踐,隨着您的系統增長這樣的複雜對象,在構建之後應該是不可改變的,這消除了關於不一致或爭用的任何顧慮。 –

+0

是的,我認爲虐待使用這種方法感謝 – nick

3

不要告訴我,我有打電話給新換的類的每個實例!

沒錯。您剛創建了一個空數組。

3
ElementInfo e[] = new ElementInfo[2]; 

e[0] = new ElementInfo(); 
e[0].symbol = 'H'; ... 
3

你必須爲每一個元素的新實例,但它並不難:

ElementInfo e[] = new ElementInfo[2]; 
for (int i = 0; i < e.length; i++) 
    e[i] = new ElementInfo(); 
2

是的,你必須做的。

當您創建數組時,您只需爲實際對象的引用創建空間。最初的價值是null

要使對象引用,你做一個分配

e[0] = new ElementInfo(); 

ElementInfo a = new ElementInfo(); 
.... 
e[0] = a; 

放鬆,打字將是最後你的問題作爲一個程序員:-D

+0

好的事情,我可以複製/粘貼和使用正則表達式:) – nick

1

通過聲明一個數組,該數組類型的實例不會自動填充數組

e[0] = new ElementInfo(); 

您還可以使用for循環輕鬆實例化每個索引處的對象。

for (int i = 0; i < e.length; i++) { 
    e[i] = new ElementInfo(); 
} 
1

是的。現在它是一個存儲ElementInfo對象的數組,但每個索引都爲null。

爲什麼不創建一個帶參數的構造函數。然後

ElementInfo [] elements = {new ElementInfo("H", "Hydrogen", 1.008), new ElementInfo("C", ....)}; 
+0

因爲也許一些元素將有更多的參數,我寧願保持這種格式 – nick

0
ElementInfo e[] = new ElementInfo[100]; 
for(ElementInfo element: e){ 
    e = new ElementInfo(); 
} 

你不能這樣做,因爲e是一個數組類型的變量,這意味着你不能給它分配一個參考的ElementInfo類型的對象。我所指的是​​。請參閱answer by Dalmus