Reputation: 317
I'm wondering about the best way to implement a matrix in Java in which columns and rows have to be easily added/removed.
Something like double[][] matrix
seems quite heavy when it comes to column/row removal.
I did some searches but could not find a design pattern (or so) dealing with this. Do you have any suggestion? I'm not looking for a library but more some guidelines on what is needed. I was thinking of a mix of Lists and Maps but I'm not sure that's the most efficient.
This link provides a bit of help but I'm sure there is a design pattern for this, or at least a nice way to do it.
Here are some more specifications: I expect the matrix to be 300x300 big in general. I need to do many manipulations though (I'm doing a heuristic that updates it a lot, hundreds times/sec), thus I can't browse it every time I want to update it. There's no maximum size but I don't expect it to be larger that 5000x5000.
Upvotes: 1
Views: 2043
Reputation: 3963
Have a look at this implementation here. It looks like what you're looking for.
Upvotes: 1
Reputation: 2618
A possible simple solution would be the use of a List of List, like
int nRows = 8, nCols = 4;
List<List<Double>> matrix = new ArrayList<>(nRows);
for (int k = 0; k < nRows; k++) {
matrix.add(new ArrayList<>(nCols));
}
In this case would be really easy to add/remove a row, but a little tricky to add/remove a column.
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));
}
}
Upvotes: 3
Reputation: 1379
I suggest you to create your own class for this, similar to this
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
}
Such thing is quite easy to implement and gives you all the flexibility you need when using
Upvotes: 1