简体   繁体   中英

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?

Thanks

Regards

First you need to decide how to parse your strings, are they different 1D arrays or all in a 2D array?  You could make a 2D array length the size of the largest array and test for nulls in the shorter ones... your simple loop would look something like this:
<code>
for (int i=0; i < 3; i++) { 
    for (int j=0; j< currentArray.length && currentArray[j] != NULL; j++) { 
        System.out.println(currentArray[i][j]);
    }
}
</code>

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

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