简体   繁体   中英

Best way to store a table of data

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 .

Two approaches:

  1. Convert everything to strings and use an ArrayList<List<String>> where each entry is a row represented by an ArrayList<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.

  2. As dystroy said, create a class representing a Row in the table, and use an ArrayList<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 (eg row.getDate() instead of row.get(3) ).
    • Disadvantage: might be more work to create the additional class.

I'd choose LinkedList especially if you expect your list to work as a Stack.

Main Drawback of ArrayList is that this one recreates a larger table when capacity is reached => table allocation and copy gets performance slower.

Whereas with LinkedList, there is no concept of capacity since all works by pointers.

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

You can read this post for more information :

When to use LinkedList over ArrayList?

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