Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I instantiate List<List<String>> in Java

Tags:

java

I have the following code:

            List<List<String>> allData= getData()
            
            if (allData== null)
                allData= new ArrayList<ArrayList<String>>();
            // populate allData below

Now I want to initialize allData but I get Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>>. What is the correct way I can initialize this?

It is not possible to return ArrayList<ArrayList<String>> from getData()

Thanks!

like image 964
anupamD Avatar asked Mar 11 '26 15:03

anupamD


2 Answers

You do it very simply:

allData = new ArrayList<>();

Then you can add new lists to allData:

List innerList = new ArrayList<>();
innerList.add("some string");
// .... etc ...
allData.add(innerList);
like image 98
DontKnowMuchBut Getting Better Avatar answered Mar 14 '26 05:03

DontKnowMuchBut Getting Better


You cannot redefine the generic type of the reference when you instantiate the concrete implementation. The reference is List<List<String>> so the assigned List must be capable of accepting any List<String> as an element. When you instantiated your instance, you attempted to limit this to ArrayList<String>.

The explicit solution is:

allData = new ArrayList<List<String>>();

or more simply as:

allData = new ArrayList<>();
like image 31
vsfDawg Avatar answered Mar 14 '26 05:03

vsfDawg