简体   繁体   中英

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 RowID. What data structure should I use and how do I implement it as in code?

Make an ArrayList of ArrayLists. Eg:

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.

您可以使用Map<Integer, ArrayList<MyObject>> ,其中地图的键将是您的RowID。

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.

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提供了列表转换,例如,您可以通过以下方式执行此操作:

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

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