简体   繁体   English

矩阵的Java数据结构?

[英]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.. 我可以简单地使用n by b数组作为矩阵,但问题是我不想浪费内存,因为矩阵中只有少数元素。

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). 使用带有行索引的HashMap作为键,然后使用HashMapTreeMap作为实际元素(列索引为键)。 If you are storing primitive types, I would suggest having a look at the Trove Java Collections Framework. 如果您要存储基元类型,我建议您查看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。 LinkedList will be better than other options in terms of space(provided the matrix is sparse). LinkedList在空间方面将优于其他选项(假设矩阵是稀疏的)。

But note that LinkedList has O(n) time for access. 但请注意LinkedList有O(n)时间访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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