Reputation: 5511
I have the following class:
private class Info{
public String A;
public int B;
Info(){};
public OtherMethod(){};
private PrivMethod(){};
}
And I want to create an array of this class, but I want to provide a two dimensional array as an argument to the constructor, ie:
Info[] I = new Info({{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
Is that possible? If so how would I implement it? If not, what alternatives would you suggest?
Upvotes: 1
Views: 958
Reputation: 57668
What advantage would that have compared to this?
Info[] infos = new Info[] {new Info("StringA", 1),
new Info("StringB", 2),
new Info("StringC", 3)
}.
Upvotes: 3
Reputation: 2446
Hope this might help!
/*
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();
}
}
Upvotes: 0
Reputation: 30449
Its possible, but not using the syntax you suggested. Java doesn't support creating arrays out of constructors. Try the following:
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}});
}
}
Upvotes: 3
Reputation: 136623
A static factory method that accepts this input as rectangular object array, creates the instances, adds it to an Info Array and returns it ?
Info[] infos = Info.CreateInfoArray( new object[][] {
{"StringA", 1},
{"StringB", 2},
{"StringC", 3} } );
Upvotes: 1