繁体   English   中英

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

[英]Java 2D string or arraylist?

我有一个字符串数据集如下:

第 1 行:“abc”、“def”、“ghi”

第 2 行:“xyz”

第 3 行:“lmn”、“opq”、“rst”、“uvw”

首先,我想遍历每一行和每一列并在窗口中输出值。

我不确定如何执行此操作,因为每行都有不同的列数。

有人能告诉我在java中初始化这个数据集的最佳方法是什么吗?

谢谢

问候

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>

选项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" });

选项 2:

如果事先知道行数,也可以这样做:

    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