简体   繁体   中英

Initialize List<List<Integer>> in Java

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?

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> .

您可以将其定义为List<List<Integer>> list = new LinkedList();

You can initialize this as

List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();

Note that the inner List has to be an implementation of the List interface, eg, ArrayList.
Since List is an interface, one can't have objects of the type List itself.

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