Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java best structure for 2D matrix of integers?

What is the best way to store a 2D matrix of integers in Java?

This matrix will be filled in from a data file, which may have different dimensions, so initializing int M[][] = new int[n][m] of some size does not work since we do not know the size of matrix and we will just iterate lines of the file and extract integers from each line (separated by a whitespace inside). So I guess to use an ArrayList of ArrayList to add integers as objects on the fly, but I'm not quite sure how to do that.

Also it is important to choose the best structure to store such matrix in terms of performance sine I'm going to iterate this matrix and do some computations.

like image 544
Sophie Sperner Avatar asked Jun 18 '12 14:06

Sophie Sperner


2 Answers

Start with an ArrayList<ArrayList<Integer>>, and then as soon as you've finished reading the file, turn it into an int[][] for performance.

like image 74
Louis Wasserman Avatar answered Sep 28 '22 09:09

Louis Wasserman


As you guessed, it would probably be best to use an ArrayList of ArrayList when you are processing the file. If performance is going to be an issue after the fact, it might be prudent to turn it back into a two dimensional array afterwords.

You can add to the two dimensional ArrayList matrix like so:

ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
matrix.add(new ArrayList<Integer>());
matrix.get(0).add(ROW0Col0Number);
matrix.get(0).add(ROW0Col1Number);
matrix.get(1).add(ROW1Col0Number);
like image 20
NominSim Avatar answered Sep 28 '22 09:09

NominSim