Vignesh Suresh Vignesh Suresh - 2 years ago 131
Java Question

Java 2D string or arraylist?

I had a string dataset as follows:

row 1: "abc', "def", "ghi"

row 2: "xyz"

row 3: "lmn", "opq", "rst", "uvw"

For the start I would like to loop over each row and column and output the values in a window.

I was not sure of how to do this since, each row has different number of columns.

Could someone please tell me what would be the best way to initialize this dataset in java?



Answer Source

Option 1:

    List<String[]> dataSet = new ArrayList<String[]>();

    dataSet.add(new String[] { "abc", "def", "ghi" });
    dataSet.add(new String[] { "xyz" });
    dataSet.add(new String[] { "lmn", "opq", "rst", "uvw" });

Option 2:

If you know the number of rows in advance, you can also do this:

    int numRows = 3; //if you know the number of rows in advance
    String[][] dataSet2 = new String[numRows][]; 

    dataSet2[0] = new String[] { "abc", "def", "ghi" };
    dataSet2[1] = new String[] { "xyz" };
    dataSet2[2] = new String[] { "lmn", "opq", "rst", "uvw" };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download