How can I initialize List<List<Integer>>
in Java?
I know List
is an interface and I can use ArrayList
or LinkedList
to implement List<Integer> list = new ArrayList<Integer>()
, but when I initialize List<List<Integer>> list = new ArrayList<ArrayList<Integer>>();
I get error incompatible types:
ArrayList<ArrayList<Integer>> cannot be converted to List<List<Integer>>.
So how can I proceed?
You can do this as follows but have to give up on generics for the list container. List<List> listOfMixedTypes = new ArrayList<List>(); ArrayList<String> listOfStrings = new ArrayList<String>(); ArrayList<Integer> listOfIntegers = new ArrayList<Integer>(); listOfMixedTypes. add(listOfStrings); listOfMixedTypes.
The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
Use
List<List<Integer>> list = new ArrayList<List<Integer>>();
or since Java 1.7
List<List<Integer>> list = new ArrayList<>();
You can define it as List<List<Integer>> list = new ArrayList<List<Integer>>();
.
Then while defining the inner List
you can take care of initialising it as ArrayList<Integer>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With