[英]Best way to represent a Matrix (2D-Array) of variable length in Java?
I want to create a matrix with a variable number of rows which is filled during runtime.我想创建一个在运行时填充的行数可变的矩阵。 The number of rows depends on the data and is not known before the program starts.行数取决于数据,在程序启动之前是未知的。 What I tried is this:我试过的是这样的:
ArrayList<HashMap<Integer, Double>> eMatrix = new ArrayList<HashMap<Integer, Double>>();
HashMap<Integer, Double> row = new HashMap<Integer, Double>();
while (i < foo.size() - 1) {
if (foo.get(i) == 0) {
row.put(0, foo.get(i));
}
if (foo.get(i) == 1) {
ro.put(1, foo.get(i));
}
if (foo.get(i) == 2) {
ro.put(2, foo.get(i));
}
if (!row.isEmpty()) {
eMatrix.add(row);
}
row.clear();
i++;
}
The idea was that as ArrayLists and HashMaps can have variable size to create rows with the HashMap, and add these rows to the ArrayList resulting in a matrix.这个想法是因为 ArrayLists 和 HashMaps 可以具有可变大小以使用 HashMap 创建行,并将这些行添加到 ArrayList 产生矩阵。 Now the problem is that row.clear
clears the entries in eMatrix
as well.现在的问题是row.clear
清除eMatrix
的条目。 Do you have a better idea how to do it?你有更好的主意怎么做吗?
Your specific implementation problem can be solved by creating a new HashMap
instance for each row of the matrix :您的具体实现问题可以通过为矩阵的每一行创建一个新的HashMap
实例来解决:
ArrayList<HashMap<Integer, Double>> eMatrix = new ArrayList<HashMap<Integer, Double>>();
while (i < foo.size() - 1) {
HashMap<Integer, Double> row = new HashMap<Integer, Double>();
if (foo.get(i) == 0) {
row.put(0, foo.get(i));
}
if (foo.get(i) == 1) {
ro.put(1, foo.get(i));
}
if (foo.get(i) == 2) {
ro.put(2, foo.get(i));
}
if (!row.isEmpty()) {
eMatrix.add(row);
}
i++;
}
That said, I would still try to use a simple 2D array ( double[][]
).也就是说,我仍然会尝试使用一个简单的二维数组( double[][]
)。 You can initialize it at run time, once you know the required dimensions of the matrix.一旦您知道矩阵的所需维度,您就可以在运行时对其进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.