[英]initialize two dimensional string array with dynamic size in java
我的記錄數未知,我需要將所有記錄放入字符串二維數組中。
我不知道記錄的數量,因此,不知道字符串2d數組初始化所需的行數和列數。
目前我正在使用如下:
String[][] data = new String[100][100];
在這里,我對行和列的數量進行了硬編碼,但需要在字符串2d數組中允許的動態大小。 任何建議請!
Rgrds
您可以使用以下類將數據存儲在HashMap
,並將其轉換為二維字符串數組。
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
您可以臨時將它們存儲在List<String[]>
並使用List#toArray(String[])
將其轉換為二維數組。
例
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new FileReader(new File(
"data.txt")));
String line;
List<String[]> list = new ArrayList<String[]>();
while ((line = r.readLine()) != null)
list.add(line.split(" +"));
String[][] data = new String[list.size()][];
list.toArray(data);
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();
}
r.close();
}
數據文件
1 2 3 4 5
2 5 3
2 5 5 8
輸出量
1 2 3 4 5
2 5 3
2 5 5 8
您可以簡單地使用文字,空的二維數組進行初始化:
String[][] data = new String[][]{{}}
這應該工作:
public static void main(String args[]) throws IOException {
// create the object
String[][] data;
// ----- dinamically know the matrix dimension ----- //
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int r = Integer.parseInt(bufferedReader.readLine());
int c = Integer.parseInt(bufferedReader.readLine());
// ------------------------------------------------ //
// allocate the object
data = new String[r][c];
// init the object
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
data[i][j] = "hello";
}
在此示例中,您知道矩陣維運行時,可通過控制台手動指定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.