简体   繁体   中英

How to implement a class constructor accepting an array of different types as an argument in Java

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?

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

}

What advantage would that have compared to this?

Info[] infos = new Info[] {new Info("StringA", 1),
                           new Info("StringB", 2),
                           new Info("StringC", 3)
                      }.

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM