2013-03-06 87 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的匿名实例。