js0823
js0823

Reputation: 1873

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?

Upvotes: 5

Views: 21292

Answers (6)

kiedysktos
kiedysktos

Reputation: 4100

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

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

Upvotes: 0

Scott
Scott

Reputation: 136

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.

Upvotes: 3

Rafe Kettler
Rafe Kettler

Reputation: 76955

Make an ArrayList of ArrayLists. E.g.:

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

Upvotes: 15

mR_fr0g
mR_fr0g

Reputation: 8722

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

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

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.

Upvotes: 6

user439793
user439793

Reputation:

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.

Upvotes: 1

Related Questions