Java动态矩阵结构

时间:2014-11-21 08:14:35

标签: java matrix data-structures

我想知道在Java中实现矩阵的最佳方法,其中必须轻松添加/删除列和行。

当删除列/行时,double[][] matrix之类的东西似乎很重。

我做了一些搜索,但找不到处理此问题的设计模式(或左右)。你有什么建议吗?我不是在寻找图书馆,而是更多关于需要的指南。我想的是列表和地图的混合,但我不确定它是最有效的。

这个link提供了一些帮助,但我确信有一个设计模式,或者至少是一个很好的方法。

以下是一些更多规范:我希望矩阵一般为300x300。我需要做很多操作(我正在做一个启发式,它会更新它,数百次/秒),因此每次我想要更新它时我都无法浏览它。没有最大尺寸,但我不希望它大于5000x5000。

3 个答案:

答案 0 :(得分:3)

一个可能的简单解决方案是使用List of List,比如

int nRows = 8, nCols = 4;
List<List<Double>> matrix = new ArrayList<>(nRows);
for (int k = 0; k < nRows; k++) {
    matrix.add(new ArrayList<>(nCols));
}

在这种情况下添加/删除行非常容易,但添加/删除列有点棘手。

void removeRow(ArrayList<ArrayList<Double>> matrix, int rowIndexToRemove) {
    matrix.remove(rowIndexToRemove);
}

void removeColumn(ArrayList<ArrayList<Double>> matrix, int coulmnIndexToRemove) {
    for (ArrayList<Double> row : matrix) {
        row.remove(coulmnIndexToRemove);
    }
}

void addRow(ArrayList<ArrayList<Double>> matrix, int rowIndexWhereInsert, ArrayList<Double> newRow) {
    matrix.add(rowIndexWhereInsert, newRow);
}

void addColumn(ArrayList<ArrayList<Double>> matrix, int columnIndexWhereInsert, ArrayList<Double> newColumn) {
    for (int k = 0; k < matrix.size(); k++) {
        ArrayList<Double> row = matrix.get(k);
        row.add(columnIndexWhereInsert, newColumn.get(k));
    }        
}

答案 1 :(得分:1)

我建议您为此创建自己的类,类似于此

class Matrix{
int rows
int cols
List<MatrixElement> elements;
//some methods like getCols(), getRows()
}

class MatrixElement{
int row
int col
double value
//some methods like boolean isNeighbourOf(MatrixElement other) etc whatever you need

}

这样的事情很容易实现,并且在使用

时为您提供所需的所有灵活性

答案 2 :(得分:1)

看看这个实现here。它看起来像你正在寻找的东西。