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.
Start with an ArrayList<ArrayList<Integer>>
, and then as soon as you've finished reading the file, turn it into an int[][]
for performance.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With