java 存储数据表的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10416653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to store a table of data
提问by HarryB
I have a table of data (the number of columns can vary in length on different rows). I also need to be able to delete or add new rows of data.
我有一个数据表(不同行的列数的长度可能不同)。我还需要能够删除或添加新的数据行。
What is the best way to store this data?
存储这些数据的最佳方式是什么?
My first guess would be an ArrayList
.
我的第一个猜测是ArrayList
.
回答by trutheality
Two approaches:
两种做法:
Convert everything to strings and use an
ArrayList<List<String>>
where each entry is a row represented by anArrayList<String>
.- Advantage: Don't need to create your own class to represent a "row".
- Disadvantage: Need to convert data, can't do mathematical operations without converting data back, need to make sure all rows are the same length.
As dystroy said, create a class representing a
Row
in the table, and use anArrayList<Row>
- Advantage: entries keep their actual types, rows don't have variable lengths (unless you want them to), and you can have meaningful ways to access columns (e.g.
row.getDate()
instead ofrow.get(3)
). - Disadvantage: might be more work to create the additional class.
- Advantage: entries keep their actual types, rows don't have variable lengths (unless you want them to), and you can have meaningful ways to access columns (e.g.
将所有内容转换为字符串并使用 ,
ArrayList<List<String>>
其中每个条目是由ArrayList<String>
.- 优点:不需要创建自己的类来表示“行”。
- 缺点:需要转换数据,不转换回数据不能做数学运算,需要保证所有行的长度相同。
正如dystroy所说,
Row
在表中创建一个代表a的类,并使用一个ArrayList<Row>
- 优点:条目保持它们的实际类型,行没有可变长度(除非你想要它们),并且你可以有有意义的方式来访问列(例如
row.getDate()
代替row.get(3)
)。 - 缺点:可能需要更多的工作来创建额外的类。
- 优点:条目保持它们的实际类型,行没有可变长度(除非你想要它们),并且你可以有有意义的方式来访问列(例如
回答by Mik378
I'd choose LinkedList especially if you expect your list to work as a Stack.
我会选择 LinkedList 特别是如果您希望您的列表作为堆栈工作。
Main Drawback of ArrayList is that this one recreates a larger table when capacity is reached => table allocation and copy gets performance slower.
ArrayList 的主要缺点是当容量达到时重新创建一个更大的表 => 表分配和复制使性能变慢。
Whereas with LinkedList, there is no concept of capacity since all works by pointers.
而在 LinkedList 中,没有容量的概念,因为都是通过指针工作的。
According to me, the main (and probably unique in mostly cases...) reason to prefer ArrayList rather than LinkedList is when you mainly want to access (read part so) a particular index. With ArrayList it is O(1), whereas with LinkedList it is O(n).
根据我的说法,更喜欢 ArrayList 而不是 LinkedList 的主要(并且在大多数情况下可能是独一无二的......)原因是当您主要想访问(阅读部分)特定索引时。对于 ArrayList,它是 O(1),而对于 LinkedList,它是 O(n)。
You can read this post for more information :
您可以阅读这篇文章了解更多信息: