如何在 Java 中表示二维矩阵?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35240044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:27:02  来源:igfitidea点击:

How to represent a 2D matrix in Java?

javamatrixdata-structures

提问by machinery

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 elements. Moreover, it should be thread-safe (threads writing at the same time). Perhaps later I need some matrix operations too.

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

Which data structure is best for this? Just a 2D array or a TreeMap? Or is there any amazing external library?

哪种数据结构最适合这个?只是一个二维数组还是一个 TreeMap?或者有什么惊人的外部库?

采纳答案by Noor Nawaz

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

您应该将 Vector 用于二维数组。它是线程安全的

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

00 01

10 11

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

看看 向量

回答by Paulo

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?

清除?

回答by Aniket Rangrej

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>>();