Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java data structure for matrix?

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..

like image 437
codereviewanskquestions Avatar asked Mar 24 '11 06:03

codereviewanskquestions


People also ask

Which data structure is used for matrix?

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.

How do you represent a matrix in Java?

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.

Does Java have a matrix class?

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.

What is matrix in data structure with example?

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.


2 Answers

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.

like image 117
Nico Huysamen Avatar answered Sep 20 '22 08:09

Nico Huysamen


There are also multiple Table implementations from Google Guava libraries

like image 41
Andrejs Avatar answered Sep 18 '22 08:09

Andrejs