2

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!

1
  • 1
    allData = new ArrayList<List<String>>(); or - even simpler - let type inference do its job: allData = new ArrayList<>();
    – Turing85
    Sep 25, 2020 at 11:13

3 Answers 3

9

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);
0
3

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<>();
1
1
A simple example of getData might be as below -
        
   public static List<List<String>> getData(String fileName){
        List<List<String>> content = null;
        try (Stream<String> lines = Files.lines(Paths.get(fileName ))) {
            content = lines
                    .map(l -> l.split(" "))
                    .map(Arrays::asList)
                    .collect(Collectors.toList());
    
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.