如果我为创建为Collection.singletonList
或Arrays.asList
, 函数接受forEach
函数中所需的使用者的必需参数为int[](for new int[]{})
或Interger[](for new Integer[]{})
似乎数组的每个元素都像大小为一的数组一样传递。因此,当我打印Arrays.toString(x)
x
类型int[]
的值时,它工作正常
Collections.singletonList(new int[] {1, 2, 3})
.forEach(new Consumer<int[]>() {
@Override
public void accept(int[] o) {
System.out.println(o);
}
});
为什么必需参数的类型是int[]
而不是 int
Collection.singletonList
创建,顾名思义,一个包含一个元素的列表 - 在您的情况下是一个数组。我假设你想要实现的是这样的
Arrays.asList(1, 2, 3).forEach(new Consumer<Integer>() {
@Override
public void accept(Integer o) {
System.out.println(o);
}
});
构建列表的方式不正确。您实际上创建了一个单例列表(即只有一个元素的列表),并且这个唯一的元素是 int[] 类型。
另请注意Consumer
旨在与 lambda 或方法引用一起使用:
Stream.of(1,2,3).forEach(System.out::println);