Reputation: 1493
Trying to create a matrix object of generic type that has int columns, rows, and values. Note: The code below uses integer type to simplify.
Example output:
21 703 22 23
3 3 13 13 6
Or
studone studtwo studthree
studfour studnine studten
studran studmoreran studplus
Attempt:
My idea: Matrix will have col, rows... so rows of x ArrayList, and cols of y ArrayList
Here is the constructor:
private ArrayList<ArrayList<Integer>> matrixOne;
public Matrix(int rows, int columns) {
this.rows = rows;
this.columns = columns;
matrixOne = new ArrayList<ArrayList<ArrayList>>();
for(int i = 0; i < rows; i++) {
matrixOne.add(new ArrayList<ArrayList>());
}
for(int j = 0; j < columns; j++) {
matrixOne.get(j).add(new ArrayList<Integer>());
}
}
ISSUE: When trying to add value to a particular row/col, I get the following error in below method: The method add(int) is undefined for the type Integer
// on method .add() <-------- error
public void insert(int row, int column, int value) {
matrixOne.get(row).get(column).add(value);
}
Upvotes: 1
Views: 1685
Reputation: 8561
I would like to suggest you to use the dimensional array instead. Following is the simple implementation for transforming list(vector) to dimensional array. Inspired by R 's matrix(vec,nrow = 3,ncol = 3)
public static void main(String[] args){
int[] vec = {2,3,4,5,6,7,8,9,10};
toMatrix(vec,3,3);//parameters: vector(list),row of expected matrix,column of expected matrix
}
public static int[][] toMatrix(int[] vec,int row ,int col){
int[][] matrix = new int[row][col];
int vecIndex = 0;//list index to pop the data out from vector
//Vector to matrix transformation
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(vecIndex==vec.length) break;
matrix[i][j] = vec[vecIndex++];//pop the vector value
}
}
// Displaying the matrix, can ignore if not necessary
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
return matrix;
}
Upvotes: 1
Reputation: 4083
You are shadowing your field
private ArrayList<ArrayList<Integer>> matrixOne;
with
ArrayList<ArrayList<ArrayList>> matrixOne = new ArrayList<ArrayList<ArrayList>>();
which doesnt have any type other than ArrayList. Try this :
matrixOne = new ArrayList<ArrayList<Integer>>();
for shadowing a class variable
Upvotes: 1
Reputation: 586
Try this:
public void insert(int row, int column, int value) {
matrixOne.get(row).add(column, value);
}
Upvotes: 0