Java动态二维矩阵
我想创建一个动态二维矩阵,其中行数和列数未知。通过一次添加一个元素来填充它。例如,第1次按钮点击 = M[1][1](此时矩阵只包含该元素),则M[1][2]、[1][3]....等。
l would like to create a dynamic 2D matrix, where the number of rows and columns is unknown. Filling it by adding one element at the time. For example, 1st button click = M[1][1] (at this time, the matrix contains only this element), then M[1][2], [1][3]....etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用集合来做到这一点。例如:
Use collections to do this. For example:
这里有一个可以考虑的选项,可以让您的二维数组保持快速处理。它以固定大小的
int[][]
数组开始,并且仅根据需要增长:Here's one option to consider to keep your 2D array fast for processing. It starts with a fixed size array of
int[][]
and grows only as necessary:您可以(1)使用哈希映射,将点映射到按钮状态,并将最大行数和列数存储在单独的变量中;或者,您可以 (2) 使用一棵树,每一行都有一个节点,并将节点添加到相应的行节点来表示矩阵条目。
您还可以 (3) 使用整数的有序动态列表(数组列表、链接列表等),其中每个整数的前 n 位可以存储行,下一个 n 位为列,其余位为与按钮状态相关的任何数据。但是,n 的大小取决于行数和列数的最大界限。从列表中检索元素时,使用按位运算符提取相关数据。
如果使用数组列表,则分配的内存量对于 (3) 来说将是最少的,但否则,由于数据结构的性质,当您添加额外元素时,每个条目都会有一些与之关联的额外数据。使用 (1) 搜索速度最快; (2) 和 (3) 都应该表现出 O(log(n)) 搜索时间,但我怀疑由于数据局部性,(3) 会明显更快。在方法(1)和(2)中,添加和删除元素的速度最快的是(1);方法(3)添加或删除元素所需的时间取决于列表的实现。
我确信还有很多其他结构可供您使用,但我没有在此处列出,但您可能需要注意,如果您可以保证行数和列数保持在合理的范围内,那么使用静态数据结构确实可以加快速度。
You could (1) use a hash map which maps points to button states and have the maximum number of rows and columns stored in separate variables; alternatively, you could (2) use a tree and have one node for each row, and add nodes to the corresponding row nodes to represent matrix entries.
You could also (3) use an ordered, dynamic list (array list, linked list, etc.) of integers, where the first n bits of each integer can store the row, the next n bits the column, and the rest of the bits any data pertaining to the state of the button. The size of n, however, depends on what your maximum bounds for the number of rows and columns are. Use bitwise operators to extract relevant data when you retrieve an element from the list.
The amount of memory allocated would be least for (3) if an array list is used, but otherwise, each entry will have some extra data associated with it when you add extra elements, due to the nature of the data structure. Searching would be fastest with (1); both (2) and (3) should exhibit O(log(n)) searching times, but I would suspect that (3) would be significantly faster because of the data locality. Of approaches (1) and (2), adding and removing elements would be fastest with (1); the time it takes for approach (3) to add or remove an element depends on the implementation of the list.
I'm sure there's plenty of other structures which you could use that I haven't listed here, but you may want to note that if you can guarantee that the number of rows and columns will remain within reasonable bounds, then using a static data structure could really speed things up.