我想使用一个集合来代替二维数组,这样我就不需要在声明时给出它的大小,而且我可以动态添加任意数量的元素。
最佳答案
List> 的问题是,如果您想重新调整矩阵,则必须重新调整每一行。
如果你想使用稀疏矩阵,或者可能是无限矩阵,你可以这样做:
class SparseMatrix<X> {
private Map<Coord, X> values = new HashMap<Coord, X>();
public SparseMatrix() {
}
public X get(int x, int y) {
return values.put(new Coord(x,y)); // null if there's no value
}
public void set(int x, int y, X value) { // you can use null (like in a List)
values.set(new Coord(x,y), value);
}
private static class Coord {
int x; int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (other instance of Coord) {
Coord o = (Coord) other;
return o.x == x && o.y == y;
}
return false;
}
@Override
public int hashCode() {
return o.x + o.y; // or some more clever implementation :)
}
}
}
编辑: Apache Commons HashCodeBuilder是生成哈希码的好工具。
关于java - 在 Java 中使用什么集合代替二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2050490/