2

我有这个

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

最初我想创建一个包含字段“id”和“desc”的数据类型数组,但似乎不可能在声明中初始化这样的数组?(我无法谷歌操作方法。)真的是这样吗?

4

4 回答 4

7

这个怎么样?

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

但请确保您有一个 Yourtype 的构造函数,它接受 int (id) 和 String 作为参数。

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

}
于 2013-03-06T21:50:23.737 回答
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.
};
于 2013-03-06T21:51:45.053 回答
3

你有没有尝试过这样的:

MyClass[] array={new MyClass(),new MyClass()};
于 2013-03-06T21:53:59.447 回答
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 数组中初始化 DataType 的匿名实例。

于 2013-03-06T21:59:39.337 回答