[英]Java8 Collection Replaceall-Method error
我希望你能帮助我,因为我是 Java-8 的新手
public class main {
public static void main(String[] args){
ArrayList<Double> coll1 = new ArrayList<>();
coll1.add(2.5);
coll1.add(3.5);
printColl(multi(coll1));
}
public static ArrayList<Double> multi(ArrayList<Double> coll1) {
return coll1.replaceAll(aDouble -> aDouble*2.0);
}
public static void printColl(ArrayList<?> coll) {
coll.stream().forEach(System.out::println);
}
}
我有以下问题:我有一个带有 2 个双精度数的 ArrayList,我正在尝试使用“multi”方法对其进行修改。 我使用方法“replaceAll”通过 lambda 表达式更改单个值,但出现错误。
错误是“类型不兼容。必需:java.util.List Found:void”
我希望你能帮助我,因为我真的不知道为什么我会收到这个错误。
让我们来看看 replaceAll 方法签名:
public void replaceAll(UnaryOperator<E> operator)
如您所见,它不返回任何内容,这意味着它修改了现有的 ArrayList。
因此,在您的情况下,您需要执行以下操作:
public static ArrayList<Double> multi(ArrayList<Double> coll1) {
coll1.replaceAll(aDouble -> aDouble*2.0);
return coll1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.