我有以下课程:
private class Info{
public String A;
public int B;
Info(){};
public OtherMethod(){};
private PrivMethod(){};
}
我想创建一个这个类的数组,但我想提供一个二维数组作为构造函数的参数,即:
Info[] I = new Info({{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
这可能吗?如果是这样我将如何实现它?如果没有,你会建议哪些替代方案?
答案 0 :(得分:3)
可能,但不使用您建议的语法。 Java不支持从构造函数创建数组。请尝试以下方法:
public class Info {
public String a;
public int b;
private Info(Object [] args) {
a = (String) args[0];
b = (Integer) args[1];
}
public static Info[] create(Object[]...args) {
Info[] result = new Info[args.length];
int count = 0;
for (Object[] arg : args) {
result[count++] = new Info(arg);
}
return result;
}
public static void main(String [] args) {
Info[] data = Info.create(new Object[][] {{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
}
}
答案 1 :(得分:3)
与此相比有什么优势?
Info[] infos = new Info[] {new Info("StringA", 1),
new Info("StringB", 2),
new Info("StringC", 3)
}.
答案 2 :(得分:1)
将此输入作为矩形对象数组接受的静态工厂方法,创建实例,将其添加到Info Array并返回它?
Info[] infos = Info.CreateInfoArray( new object[][] {
{"StringA", 1},
{"StringB", 2},
{"StringC", 3} } );
答案 3 :(得分:0)
希望这可能会有所帮助!
/*
Info.java
*/
public class Info{
public String A;
public int B;
Info(String s,int x){
A=s;
B=x;
};
public void show(){
System.out.println(A+" is "+B);
}
//public OtherMethod(){};
//private PrivMethod(){};
}
/*
MainClass.java
*/
public class MainClass {
public static void main(String[] args) {
Info in[] = {new Info("one",1),new Info("one",1),new Info("one",1)};
//System.out.println(in[0]);
in[0].show();
}
}