使用Arrays.asList创建数组列表的ArrayList

3

我试图使用 Arrays.asList 方法创建一个数组列表,但当我只有一个数组要传递给列表时,我很难达成这个目标。

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"});

2
你是指 Arrays.asList(new String[][] {{"Slot"}}); 吗? - khelwood
2个回答

7
我认为你想要使用Arrays.asList来创建一个包含字符串数组{"Slot"}List<String[]>

你可以这样做:
List<String[]> notWithArrays = Arrays.asList(new String[][] {{"Slot"}});

或者您可以显式地指定asList的泛型类型参数,像这样:

List<String[]> notWithArrays = Arrays.<String[]>asList(new String[] {"Slot"});

2
另一种方法是使用 List<String[]> notWithArrays = Collections.singletonList(new String[]{"Slot"}); - Lino

5
Arrays.asList有一个可变参数T...。你面临的问题是,Java有两种调用带有可变参数的方法的方式:
  1. 带有多个类型为T的参数。
  2. 带有单个类型为T[]的参数。

此外,Arrays.asList是泛型的,并根据其参数的类型推断类型参数T。如果只提供了单个数组类型的参数,则解释(2)优先于解释(1)。

这意味着当您编写Arrays.asList(new String[] {"x"})时,Java会将其解释为形式(2)调用,其中T = String

在有多个参数的情况下,没有混淆:Java总是将其解释为形式(1)的调用,并将T推断为String[]类型。

因此,解决方案是像 khelwood所示那样,通过将参数打包到一个额外的数组层中或显式指定泛型类型参数T来消除单个参数的歧义性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接