在Java中使用动态大小初始化二维字符串数组 [英] initialize two dimensional string array with dynamic size in java
问题描述
我的记录数未知,我需要将所有记录放入字符串二维数组中。
I have unknown number of records and I need to put all that records in string two dimensional array.
我不知道记录数,因此,不知道字符串2d数组初始化所需的行数和列数。
I don't know the number of records and due to this, don't know number of rows and columns which is required for string 2d array initialization.
当前我正在使用以下方式:
Currently I am using as below:
String[][] data = new String[100][100];
在这里,我对行和列的数量进行了硬编码,但需要在字符串2d数组中允许的动态大小。有任何建议!
Here I hard coded number of rows and columns but need something dynamic size allowable in string 2d array. Any suggestion pls!
Rgrds
推荐答案
您可以使用以下内容此类将您的数据存储在 HashMap
中,并能够将其转换为二维字符串数组。
You can use the following class which stores your data in a HashMap
and is able to convert it to a two dimensional string array.
public class ArrayStructure {
private HashMap<Point, String> map = new HashMap<Point, String>();
private int maxRow = 0;
private int maxColumn = 0;
public ArrayStructure() {
}
public void add(int row, int column, String string) {
map.put(new Point(row, column), string);
maxRow = Math.max(row, maxRow);
maxColumn = Math.max(column, maxColumn);
}
public String[][] toArray() {
String[][] result = new String[maxRow + 1][maxColumn + 1];
for (int row = 0; row <= maxRow; ++row)
for (int column = 0; column <= maxColumn; ++column) {
Point p = new Point(row, column);
result[row][column] = map.containsKey(p) ? map.get(p) : "";
}
return result;
}
}
示例代码
public static void main(String[] args) throws IOException {
ArrayStructure s = new ArrayStructure();
s.add(0, 0, "1");
s.add(1, 1, "4");
String[][] data = s.toArray();
for (int i = 0; i < data.length; ++i) {
for (int j = 0; j < data[i].length; ++j)
System.out.print(data[i][j] + " ");
System.out.println();
}
}
输出
1
4
这篇关于在Java中使用动态大小初始化二维字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!