Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

I want to have a Java 2D matrix and 1D matrix which should be thread-safe. I need to access individual rows and columns and the individual elements. Can anyone tell me which data structure is best to represent this? 

1 Answer

0 votes
by (19.7k points)

You can implement 2D array with the help of Vector which is thread-safe like below:

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

    }

Let’s say this is the example 2D matrix you have: 

00 01

10 11

You can get the specific index like below: 

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

Interested in Java? Check out this Java tutorial by Intellipaat.   

Related questions

0 votes
1 answer
0 votes
1 answer
asked May 4, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked May 9, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Mar 14, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...