This question already has answers here:
Difference between <? super T> and <? extends T> in Java [duplicate]
                                
                                    (14个回答)
                                
                        
                                去年关闭。
            
                    
我不知道为什么它不起作用。

日食中的错误消息:
BiPredicate类型的方法test(Fruit,capture#1-of扩展了Fruit)不适用于自变量(Fruit,Mango)

import java.util.function.BiPredicate;

public class PredTest {

    public static void main(String[] args) {

        class Fruit {
            public String name;
            public String color;
            Fruit(String name) {this.name = name; }
        };

        class Apple extends Fruit {
            Apple() {super("Apple");}
        };
        class Mango extends Fruit {
            Mango() {super("Mango");}
        };

        BiPredicate<Fruit, ? extends Fruit> tester = (f, nf) -> {
            System.out.println(nf.name);
            return true;
        };
        Fruit f = new Fruit("Not named");
        Apple a = new Apple();
        Mango m = new Mango();

// ########### I see error in the below line
        System.out.println(tester.test(f, m));

    }

}

最佳答案

假设您将lambda表达式更改为:

    BiPredicate<Fruit, ? extends Fruit> tester = (Fruit f, Apple nf) -> {
        System.out.println(nf.name);
        return true;
    };


您是否仍希望编译器允许将Mango传递给此BiPredicate

根据BiPredicate<Fruit, ? extends Fruit>的编译时间类型-tester-,编译器不知道是否允许Mango,因此不允许。

将您的BiPredicate更改为:

BiPredicate<Fruit, ? super Fruit> tester = (f, nf) -> {
    System.out.println(nf.name);
    return true;
};


将消除编译错误。

关于java - Java 8-通配符扩展,BiPredicate无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53428911/

10-12 05:50