简体   繁体   中英

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

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.

Google Guava库还有多个Table实现

When the matrix is sparse, its better to use LinkedList. LinkedList will be better than other options in terms of space(provided the matrix is sparse).

But note that LinkedList has O(n) time for access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM