在使用 for Each 函数时,在接受函数中传递给消费者的参数混淆

  • 本文关键字:函数 消费者 参数 for Each java
  • 更新时间 :
  • 英文 :


如果我为创建为Collection.singletonListArrays.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);

最新更新