What is the best data structure I can use for my matrix that will contain short variables but most of elements are empty..
I could simply use n by b array for the matrix but the problem is that I don't want to waste the memory because only a few elements are in the matrix..
I was going to use a linked list or a hash table but not sure which one would be the best data structure and how to implemente this..
The array data structure extends the idea of a matrix to more than two dimensions. For example, a three-dimensional array corresponds to a data cube. The array() function can be used to create an array. In the following code, a two-by-two-by-two, three-dimensional array is created.
Fig 1: A simple 4x4 matrix In order to represent this matrix in Java, we can use a 2 Dimensional Array. A 2D Array takes 2 dimensions, one for the row and one for the column. For example, if you specify an integer array int arr[4][4] then it means the matrix will have 4 rows and 4 columns.
The Java Matrix Class provides the fundamental operations of numerical linear algebra. Various constructors create Matrices from two dimensional arrays of double precision floating point numbers. Various "gets" and "sets" provide access to submatrices and matrix elements.
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. For example: A matrix with 9 elements is shown below.
I would implement a Sparse Matrix. Use a HashMap
with the row index as keys, and then either a HashMap
or TreeMap
for the actual elements (with the column index as key). If you are storing primitive types, I would suggest having a look at the Trove Java Collections Framework. It is optimized for use with primitive types. I would suggest using it anyway, as the keys could all be primitive.
There are also multiple Table implementations from Google Guava libraries
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