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 anint[][]for performance.