[英]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.