[英]How to initialize Java arrays of own types
I have this 我有这个
Integer[] picIDs = {
R.drawable.whatever
,
R.drawable.example
};
String[] picDescs = {
"test1"
,
"test2"
};
Originally I wanted to make an array of a datatype containing fields "id" and "desc", but it seems impossible to initialize such arrays in declaration? 最初我想创建一个包含字段“id”和“desc”的数据类型的数组,但似乎不可能在声明中初始化这样的数组? (I was not able to Google how-to.) Is that really so? (我无法以谷歌的方式去做。)这是真的吗?
how about this? 这个怎么样?
YourType[] arr = {new YourType(12,"abc"), new YourType(13, "xyz")};
But make sure you have a Constructor of Yourtype which accepts an int (id) and String as arguments. 但请确保您有一个Yourtype构造函数,它接受int(id)和String作为参数。
public class YourType{
String s;
int id;
public YourType(int id, String s){
this.id = id;
this.s = s;
}
}
You can do something like this: 你可以这样做:
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.
};
你有没有试过这样的:
MyClass[] array={new MyClass(),new MyClass()};
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};
So, you can define a class such as DataType and then just initialize anonymous instances of DataType in a DataType array. 因此,您可以定义一个类,如DataType,然后只在DataType数组中初始化DataType的匿名实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.