如何在Java中表示2D矩阵?

mac*_*ery 4 java matrix data-structures

我必须在Java中创建一个2D矩阵(由双值组成)以及一维向量.应该可以访问单个行和列以及单个元素.而且,它应该是线程安全的(线程同时写入).也许以后我也需要一些矩阵运算.

哪种数据结构最适合这种情况?只是2D数组或TreeMap?或者有没有令人惊叹的外部图书馆?

Pau*_*ulo 8

我给你举个例子:

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.
Run Code Online (Sandbox Code Playgroud)

明确?


Noo*_*waz 7

你应该使用Vector for 2D array.它是线程安全的.

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();
    }
Run Code Online (Sandbox Code Playgroud)

如果这是你的矩阵索引

00 01

10 11

您可以像这样获得指定索引值

Double r2c1=matrix.get(1).get(0); //2nd row 1st column
Run Code Online (Sandbox Code Playgroud)

看看 Vector

  • 你可以做得比这更好。 (2认同)

小智 5

如果您需要线程安全行为,请使用

Vector<Vector<Double>> matrix = new Vector<Vector<Double>>();
Run Code Online (Sandbox Code Playgroud)

如果您不需要线程安全行为,请使用

ArrayList<ArrayList<Double>> matrix = new ArrayList<ArrayList<Double>>();
Run Code Online (Sandbox Code Playgroud)