在Java中使用什么集合而不是2D数组?

Yat*_*oel 13 java collections

我想使用一个集合来代替2D数组,这样我就不需要在声明时给出它的大小,我可以动态地添加任意数量的元素.

hel*_*ios 7

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 :)
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

编辑: Apache Commons HashCodeBuilder是一个生成哈希码的好工具.