[英]Convert ArrayList<ArrayList<String>> to List<List<String>> - Java
I have a function that has to output a List<List<String>>
我有一个 function 必须 output 一个
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>>
:但是,我需要在 function 中动态添加元素,所以我只有一个
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).
我认为当您实现一个列表接口时,它需要由 class(链表、arraylist 等)定义。 So I didn't even know that you could create a
List<List<String>>.
所以我什至不知道你可以创建一个
List<List<String>>.
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.您不需要将 ArrayList 指定为变量类型。 In fact, you should never specify ArrayList anywhere, except during construction.
事实上,你不应该在任何地方指定 ArrayList,除了在构造期间。 The contract of
List
specifies all the methods you need. List
的契约指定了您需要的所有方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.