如何实现嵌套ArrayList?
我想实现一个看起来像这样的数据结构。
{{RowID, N1, N2, N3},
{RowID, N4, N5, N6},
{RowID, N7, N8, N9}}
并继续。它基本上是一个具有 3 列和 RowID 的 Java 表格。 我应该使用什么数据结构以及如何在代码中实现它?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
创建一个 ArrayList 的 ArrayList。例如:
Make an ArrayList of ArrayLists. E.g.:
有几种选择。一种方法是声明一个代表行的类。
显然,您选择了适当的数据类型和变量名称。
然后您可以创建此类型的 ArrayList:
如果列数不会变化,这尤其有用。
There are several options. One way is to declare a class that represents a row.
Obviously you choose appropriate data types and variable names.
Then you can create an ArrayList of this type:
This is especially useful if the number of columns will not vary.
假设 RowID 是 long 并且列数据是 Doubles,我会将此构造实现为:
<代码>
存储一行:
<代码>
访问一行:
<代码>
将 Double[] 替换为您想要的任何数据类型 Int[]、String[]、Object[] ...
您可以使用迭代器循环访问这些数据:
<代码>
要按照插入数据的顺序迭代数据,请使用 LinkedHashMap 代替 HashMap。
Assuming that RowID is a long and the column data are Doubles, I would implement this construct as:
To store a row:
To access a row:
Replace Double[] with whatever data type you desire Int[], String[], Object[] ...
You may loop through this data with an iterator:
To iterate the data in the order data was inserted, use LinkedHashMap in place of HashMap.
您可以使用
Map>
,其中映射的键是您的 RowID。You could use a
Map<Integer, ArrayList<MyObject>>
where the key to the map would be your RowID.我将创建一个包含每行数据的 bean 对象。这比“嵌套 ArrayList”有优势,因为数据成员是强类型的。
接下来,我会将这些 bean 插入到一个列表中,可能是一个链接列表,除非您提前知道它们的数量。如果是这样,我会切换到 ArrayList。
如果顺序不重要,您可以使用 HashSet 或 HashMap,具体取决于您是仅迭代它们 (Set) 还是需要通过 RowID (Map) 进行键查找。如果您使用这些数据结构之一,则需要为您的 bean 重写
equals()
和hashCode()
。I would create a bean object that contains the data for each row. That has an advantage over a "nested ArrayList" because the data members are strongly-typed.
Next, I would insert these beans into a List, probably a LinkedList unless you know the number of them ahead of time. If so, I would switch to an ArrayList.
If order is not important, you could use a HashSet or HashMap instead, depending on if you are only iterating them (Set) or need to do key lookups by RowID (Map). If you use one of these data structures, you will need to override
equals()
andhashCode()
for your bean.Java 提供了列表转换,因此您可以通过以下方式执行此操作:
Java provides list casting, so for example you can do this in following way: