-1

I have a function that has to output a List<List<String>>

public List<List<String>> suggestedProducts(String[] products, String searchWord)

However, I needed to add elements dynamically in the function, so I only have an ArrayList<ArrayList<String>>:

ArrayList<ArrayList<String>> output = new ArrayList<ArrayList<String>>();

I get an error when outputting this that:

error: incompatible types: ArrayList<ArrayList<String>> cannot be converted to List<List<String>>

What is the simplest way to convert this?

Can you also explain why I need to convert in the first place? I thought that when you implement a list interface it needs to be defined by a class (linked list, arraylist,etc). So I didn't even know that you could create a List<List<String>>.

user280339
  • 69
  • 1
  • 8

1 Answers1

3

Change this:

ArrayList<ArrayList<String>> output = new ArrayList<ArrayList<String>>();

to this:

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

You don’t need to specify ArrayList as a variable type. In fact, you should never specify ArrayList anywhere, except during construction. The contract of List specifies all the methods you need.

VGR
  • 40,506
  • 4
  • 48
  • 63