java - 使用 Arrays.asList 创建数组的 ArrayList

标签 java arrays

这个问题在这里已经有了答案:





Can I create a list of array with Arrays.asList?

(6 个回答)



trouble initialize List<Object[]> Using Arrays.asList

(7 个回答)


8 个月前关闭。




我正在尝试使用方法 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。有没有一种方法或方法可以使数组列表 notWithArrays 无需手动创建?
手动创建示例:
List<String[]> withArraysManual = new ArrayList<>();
withArraysManual.add(new String[] {"Slot"});

最佳答案

我想你想创建一个 List<String[]>使用 Arrays.asList , 包含字符串数组 {"Slot"} .
你可以这样做:

List<String[]> notWithArrays = Arrays.asList(new String[][] {{"Slot"}});
或者您可以显式指定泛型类型参数给 asList , 像这样:
List<String[]> notWithArrays = Arrays.<String[]>asList(new String[] {"Slot"});

关于java - 使用 Arrays.asList 创建数组的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66564613/

相关文章:

java - RepaintManager 可以对组件的损坏区域进行动画处理?

JavaCv/OpenCv 错误 : what does it mean?

java - 尝试将二维数组顺时针旋转 90 度,但它是逆时针旋转

javascript - 我的 JavaScript 代码中的索引越界错误

javascript - 操作数组 ["delete", "cancel"] 和由字符串 "01"确定的权限

java - 为什么 Canvas 会覆盖 Android Studio 中的所有其他内容?

java - 保护 Flex-BlazeDS 应用程序的最佳方法是什么?

java - 从另一个类访问数据

c++ - 数组的大小

c - 在线练习技术面试,我错过了什么?