使用Arrays.asList创建数组的ArrayList
我正在尝试使用 Arrays.asList 方法创建数组的 ArrayList,但是当我只有一个数组要传递到列表时,我正在努力实现这一目标。
List<String[]> notWithArrays = Arrays.asList(new String[] {"Slot"}); // compiler does not allow this
List<String[]> withArrays = Arrays.asList(new String[] {"Slot"},new String[] {"ts"}); // this is ok
问题是有时我只有一个数组作为参数传递,并且因为它只是一个可迭代方法 asList 从中创建字符串列表而不是所需的 List<String[]>。有没有一种方法或方法可以使数组列表notWithArrays无需手动创建?
手动创建示例:
List<String[]> withArraysManual = new ArrayList<>();
withArraysManual.add(new String[] {"Slot"});
回答
我想你想创建一个List<String[]>using Arrays.asList,包含字符串数组{"Slot"}。
你可以这样做:
List<String[]> notWithArrays = Arrays.asList(new String[][] {{"Slot"}});
或者您可以显式指定泛型类型参数为asList,如下所示:
List<String[]> notWithArrays = Arrays.<String[]>asList(new String[] {"Slot"});
- Another way would be to use `List<String[]> notWithArrays = Collections.singletonList(new String[]{"Slot"});`
回答
Arrays.asList有一个可变参数,T...。您面临的问题是 Java 有两种方法可以使用 vararg 参数调用方法:
- 具有多个类型的参数
T - 使用类型的单个参数
T[]
此外,Arrays.asList是泛型的,并T从其参数的类型推断类型参数。如果只给出一个数组类型的参数,则解释 (2) 优先。
这意味着当您编写 时Arrays.asList(new String[] {"x"}),Java 将其解释为对形式 (2) 的调用T = String。
使用多个参数不会造成混淆:Java 总是将其解释为形式 (1) 的调用,并推断T为类型String[]。
因此,正如 khelwood 所展示的,解决方案是使用单个参数消除调用的歧义,方法是将参数打包到额外的数组层中,或者通过显式指定泛型类型参数T。