2013-03-06 90 views
2

我有這個如何初始化自己的類型

Integer[] picIDs = {    
    R.drawable.whatever 
    , 
    R.drawable.example 
}; 
String[] picDescs = { 
    "test1" 
    , 
    "test2"  
};  

本來我想讓包含字段「id」和「降序」數據類型的數組的Java數組,但似乎不可能在初始化這樣的數組宣言? (我沒有能夠谷歌如何。)是真的嗎?

回答

7

這個怎麼樣?

YourType[] arr = {new YourType(12,"abc"), new YourType(13, "xyz")}; 

但要確保你有Yourtype的構造函數,它接受一個int(ID)和字符串作爲參數。

public class YourType{ 
String s; 
int id; 
    public YourType(int id, String s){ 
    this.id = id; 
    this.s = s; 
    } 

} 
+0

wut是'YourType'? – 2013-03-06 21:51:02

+0

@SamIam這是你創建的一個類,你命名爲'YourType' – nos 2013-03-06 21:51:47

+0

@PremGenError也許你應該在你的回答中以某種方式提及,以便OP不會感到困惑 – 2013-03-06 21:52:21

4

你可以做這樣的事情:

public class Item { 
    public int id; 
    public String desc; 
    public Item(int id, String desc) { 
     this.id = id; 
     this.desc = desc; 
    } 
} 

Item[] items = { 
    new Item(1, "one"), 
    new Item(2, "two") 
    // etc. 
}; 
3

您是否嘗試過一些這樣的:

MyClass[] array={new MyClass(),new MyClass()}; 
1
class DataType { 
    private Integer id; 
    private Stirng desc; 
    public DataType(Integer id, String desc) { this.id = id; this.desc = desc;} 
} 

DataType[] dt = {new DataType(id1, desc1), new DataType(id2, desc2) and so on}; 

所以,你可以定義一個類,如數據類型和然後在DataType數組中初始化DataType的匿名實例。