首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >试图用ArrayList创建一个矩阵?

试图用ArrayList创建一个矩阵?
EN

Stack Overflow用户
提问于 2018-03-30 06:35:18
回答 3查看 1.5K关注 0票数 1

尝试创建具有int列、行和值的泛型类型的矩阵对象。注意:下面的代码使用整数类型来简化。

示例输出:

代码语言:javascript
复制
21  703   22   23   

3   3   13  13  6

代码语言:javascript
复制
   studone   studtwo  studthree

   studfour  studnine studten

   studran  studmoreran studplus

企图:

  • 决定创建一个ArrayList,因为它的大小可以扩展。
  • 我的想法是:矩阵会有更多的.所以x ArrayList的行数和y ArrayList的科尔数
代码语言:javascript
复制
- Not able to test the code but I feel there must be a better way, the for loop seems excessive?

下面是构造函数:

代码语言:javascript
复制
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类型定义

代码语言:javascript
复制
 // on method .add()      <-------- error
public void insert(int row, int column, int value) {
    matrixOne.get(row).get(column).add(value);
} 
EN

回答 3

Stack Overflow用户

发布于 2018-03-30 06:43:39

你在跟踪你的领域

代码语言:javascript
复制
private ArrayList<ArrayList<Integer>> matrixOne;

使用

代码语言:javascript
复制
ArrayList<ArrayList<ArrayList>> matrixOne = new ArrayList<ArrayList<ArrayList>>();

除了ArrayList没有其他类型。试试这个:

代码语言:javascript
复制
matrixOne = new ArrayList<ArrayList<Integer>>();

对于shadowing a class variable

票数 1
EN

Stack Overflow用户

发布于 2018-03-30 07:50:15

我建议你用维数组代替。下面是将列表(向量)转换为维数组的简单实现。受R 's matrix(vec,nrow = 3,ncol = 3)的启发

代码语言:javascript
复制
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;
}
票数 1
EN

Stack Overflow用户

发布于 2018-03-30 06:39:14

试试这个:

代码语言:javascript
复制
public void insert(int row, int column, int value) {
    matrixOne.get(row).add(column, value);
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49569600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档