How to represent a 2D matrix in Java?

后端 未结 3 338
余生分开走
余生分开走 2020-12-31 17:11

I have to create in Java a 2D matrix (consisting of double values) as well as a 1D vector. It should be possible to access individual rows and columns as well as individual

相关标签:
3条回答
  • 2020-12-31 17:27

    I'll give you an example:

    int rowLen = 10, colLen = 20;   
    Integer[][] matrix = new Integer[rowLen][colLen];
    for(int i = 0; i < rowLen; i++)
        for(int j = 0; j < colLen; j++)
            matrix[i][j] = 2*(i + j); // only an example of how to access it. you can do here whatever you want.
    

    Clear?

    0 讨论(0)
  • 2020-12-31 17:39

    You should use Vector for 2D array. It is threadsafe.

    Vector<Vector<Double>>  matrix= new Vector<Vector<Double>>();
    
        for(int i=0;i<2;i++){
            Vector<Double> r=new Vector<>();
            for(int j=0;j<2;j++){
                r.add(Math.random());
            }
            matrix.add(r);
        }
        for(int i=0;i<2;i++){
            Vector<Double> r=matrix.get(i);
            for(int j=0;j<2;j++){
                System.out.print(r.get(j));
            }
            System.out.println();
        }
    

    If this is your matrix indexes

    00 01

    10 11

    You can get specifix index value like this

    Double r2c1=matrix.get(1).get(0); //2nd row 1st column
    

    Have a look at Vector

    0 讨论(0)
  • 2020-12-31 17:45

    If you need thread safe behavior, use

    Vector<Vector<Double>> matrix = new Vector<Vector<Double>>();
    

    If you don't need thread safe behavior, use

    ArrayList<ArrayList<Double>> matrix = new ArrayList<ArrayList<Double>>();
    
    0 讨论(0)
提交回复
热议问题