tl;dr
Use an ArrayList.
Answer
Java offers lots of data structures to choose from with the built in Collections.
The decision which one to use is highly dependent on the nature of the specific use case.
Usually it's a tradeoff between flexibillity and performance.
From the sparse description you provided I assume that your
requirements to the data structure are more or less the following
- Don't know or care about the number of elements
- A data structure that keeps the order of the elements
- A need to access the elements by an index
While the latter two are fullfilled by a Java array the first one is not since arrays have a fixed size.
Unless there are more specific requirements I'd suggest to use an ArrayList.
As an example I create lists of random Numbers and random length in somethingThatReturnsAList().
Of cause you can use other value-types than Numbers here.
Also, it should be possible to use completely different value-types for each list entry.
The list of lists, that you asked for is created in the main method at the end.
printThat() just prints contents of the number-lists for each index of the list
of lists with the help of a StringBuilder.
import java.util.ArrayList;
import java.util.List;
public class ListTest {
public static List<Number> somethingThatReturnsAList() {
int count;
int value;
List<Number> result;
// Random number of elements.
count = (int) (Math.random() * 10);
result = new ArrayList<Number>(count);
for (int i = 0; i < count; ++i) {
// Random value.
value = (int) (Math.random() * 10);
result.add(value);
}
return result;
}
public static void printThat(List<List<Number>> listOfLists) {
StringBuilder bldr;
List<Number> subList;
bldr = new StringBuilder();
bldr.append("The contents:\n");
for (int i = 0; i < listOfLists.size(); ++i) {
// Top list index.
bldr.append(i).append(": ");
subList = listOfLists.get(i);
// List sub list values.
for (int j = 0; j < subList.size(); ++j) {
if (j > 0) {
bldr.append(", ");
}
bldr.append(subList.get(j));
}
System.out.println(bldr.toString());
bldr.setLength(0);
}
}
public static void main(String[] args) {
int size;
List subList;
List<List<Integer>> listOfLists;
size = 5;
// Create that list of lists
listOfLists = new ArrayList<List<Integer>>(5);
for (int i = 0; i < size; ++i) {
subList = somethingThatReturnsAList();
listOfLists.add(subList);
}
// Print that list of lists
printThat(listOfLists);
}
}
This prints something like:
The contents:
0: 5, 1, 2
1:
2: 4, 2, 9, 3, 0, 7, 6
3: 0, 1, 5, 7, 6, 5, 1, 4, 5
4: 7
Object[] population = new Object[size];to create the array, then aforloop similar to the JS one to populate it.