简体   繁体   English

Java 2D 字符串或数组列表?

[英]Java 2D string or arraylist?

I had a string dataset as follows:我有一个字符串数据集如下:

row 1: "abc', "def", "ghi"第 1 行:“abc”、“def”、“ghi”

row 2: "xyz"第 2 行:“xyz”

row 3: "lmn", "opq", "rst", "uvw"第 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?有人能告诉我在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:选项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:选项 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" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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