Reputation: 33
Is there a way I can add an arbitrary number of lists within a list in java?
For example:
List<List<T>, List<T>, List<T>>
I know this is incorrect syntax, but I want to do something like that.
Upvotes: 1
Views: 272
Reputation: 82919
In case you meant arbitrarily nested lists of lists of lists of lists... you might want to use a tree structure instead, something like this:
class Tree<T> {
T element;
List<Tree<T>> children;
}
Or this, if you want to separate intermediate layers and values:
interface Tree<T> {
}
class TreeNode<T> implements Tree<T> {
List<Tree<T>> children;
}
class TreeLeaf<T> implements Tree<T> {
T element;
}
Upvotes: 1
Reputation: 26512
Assuming you have lists list1
, list2
, ..., listN
, there are multiple ways you could go about this:
Create your own class for a n-tuple:
This methodology will allow you to limit your tuple to a specific size, without having to re-implement the methods of the Collection
or List
classes.
public class ThreeTuple<A, B, C> {
private final A first;
private final B second;
private final C third;
public ThreeTuple(A first, B second, C third) {
this.first = first;
this.second = second;
this.third = third;
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
public C getThird() {
return third;
}
}
public class OtherClass {
public static void main(String[] args) {
new ThreeTuple(list1, list2, list3);
}
}
Add n lists to a list: This methodology is definitely the simplest, but does not bound the list.
List<List<T>> lists = new ArrayList<T>();
lists.add(list1);
lists.add(list2);
lists.add(list3);
Upvotes: 0
Reputation: 15189
List<List<T>>
will hold any number of List<T>
. For example:
List<List<T>> listOfLists = new ArrayList<List<T>>();
for (int i = 0; i < 10; i++) { // 10 is arbitrary here; just an example
listOfLists.add(new ArrayList<T>());
}
Without being more information about use cases or why you'd want to do this, I can't be more specific.
Upvotes: 6