-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
  • 45
  • 1
  • 6

2 Answers2

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
  • 37,458
  • 4
  • 42
  • 54
0

The problem is this:

  • ArrayList<String> implements List as List<String>
  • AL<AL<String>> does not implement List<List<String>>

see: Java wildcard "?"

Option 1:

Just use ArrayLists everywhere to reduce complexity.

public ArrayList<ArrayList<String>> sP(...);

Option 2:

Set return type as such:

public List<? extends List<String>> sP(...);

Remember that both classes and interfaces are
"extended" inside diamond operators

Using this method, you may need to cast the
returned object afterwards

Option 3:

somehow manage to do this:
a) leave the return type as it is

b) (creating a new object for this time)

return new ArrayList<List<String>>;