尝试创建具有int列、行和值的泛型类型的矩阵对象。注意:下面的代码使用整数类型来简化。
示例输出:
21 703 22 23
3 3 13 13 6或
studone studtwo studthree
studfour studnine studten
studran studmoreran studplus企图:
- Not able to test the code but I feel there must be a better way, the for loop seems excessive?
下面是构造函数:
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>());
}
}问题:当试图向特定行/col添加值时,我在下面的方法中得到以下错误:方法add(int)未为Integer类型定义
// on method .add() <-------- error
public void insert(int row, int column, int value) {
matrixOne.get(row).get(column).add(value);
} 发布于 2018-03-30 06:43:39
你在跟踪你的领域
private ArrayList<ArrayList<Integer>> matrixOne;使用
ArrayList<ArrayList<ArrayList>> matrixOne = new ArrayList<ArrayList<ArrayList>>();除了ArrayList没有其他类型。试试这个:
matrixOne = new ArrayList<ArrayList<Integer>>();发布于 2018-03-30 07:50:15
我建议你用维数组代替。下面是将列表(向量)转换为维数组的简单实现。受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;
}发布于 2018-03-30 06:39:14
试试这个:
public void insert(int row, int column, int value) {
matrixOne.get(row).add(column, value);
} https://stackoverflow.com/questions/49569600
复制相似问题