views:

173

answers:

4

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?

+1  A: 

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} } );
Gishu
+3  A: 

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}});
    }

}
Kevin
That was very helpful :) Thanks!
alkar
A: 

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();
}

}
Webbisshh
+3  A: 

What advantage would that have compared to this?

Info[] infos = new Info[] {new Info("StringA", 1),
                           new Info("StringB", 2),
                           new Info("StringC", 3)
                      }.
Zed
In fact, simplified syntax
alkar
Comparing your example to this, you save about twenty characters, but lose type checking.Once you start generating your input in a loop, even that advantage is lost anyway.
Zed
+1. If Info needs a String and an int, its constructor should take a String and an int, period. If you're receiving external data as a set of arrays, you could use a static method or a factory for creating the Info objects from those arrays, but the constructor should not take an arbitrary array of objects when that is not what it needs.
ColinD