开发者

How do I implement nested ArrayList?

I want to implement a data structure which looks something like this.

{{RowID, N1, N2, N3},
 {RowID, N4, N5, N6},
 {RowID, N7, N8, N9}}

And goes on. It basically is a table in Java with 3 columns and R开发者_C百科owID. What data structure should I use and how do I implement it as in code?


Make an ArrayList of ArrayLists. E.g.:

ArrayList<ArrayList> arrayListOfLists = new ArrayList<ArrayList>();
arrayListOfLists.add(anotherArrayList);
//etc...


There are several options. One way is to declare a class that represents a row.

 public class MyRow{
     private long rowId;
     private int col1;
     private int col2;
     private int col3;
     //etc
 }

Obviously you choose appropriate data types and variable names.

Then you can create an ArrayList of this type:

   List<MyRow> rows = new ArrayList<MyRow>();

This is especially useful if the number of columns will not vary.


Assuming that RowID is a long and the column data are Doubles, I would implement this construct as:

import java.util.HashMap;
import java.util.Map;
...
Map<Long, Double[]> table = new HashMap<Long, Double[]>();

To store a row:

Long rowID = 1234L;
table.put(rowID, new Double {0.1, 0.2, 0.3});

To access a row:

Double[] row = table.get(rowID);

Replace Double[] with whatever data type you desire Int[], String[], Object[] ...

You may loop through this data with an iterator:

import java.util.Iterator;
import java.util.Map.Entry;
...
Iterator<Entry<Long, Double[]>> iter = table.entrySet().iterator();
while (iter.hasNext()) {
    Entry entry = iter.next();
    rowID = entry.getKey();
    row = entry.getValue();
};

To iterate the data in the order data was inserted, use LinkedHashMap in place of HashMap.


You could use a Map<Integer, ArrayList<MyObject>> where the key to the map would be your RowID.


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() and hashCode() for your bean.


Java provides list casting, so for example you can do this in following way:

ArrayList<List<someObject>> ArrayListOfLists = new ArrayList<List<someObject>>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜