我正在阅读通配符,但我有点困惑。我真的不明白为什么 ifPresent 方法需要? super T
.
public void ifPresent(Consumer<? super T> consumer)
为什么不只是 T 工作?
我已经阅读了有关 PECS 的内容,并且很清楚它是如何用于类方法的,例如,但是为什么它会出现在界面中,我很乐意提供帮助。
最可能的原因是允许Consumer
s 的类型更广泛T
(与 兼容的类型T
)能够用于consumer
参数。
下面是一个例子:
Optional<String> opt = Optional.of("abc");
Optional<Integer> intOptional = Optional.of(2);
Consumer<Object> printConsumer = System.out::println;
opt.ifPresent(printConsumer);
intOptional.ifPresent(printConsumer);
Run Code Online (Sandbox Code Playgroud)
printConsumer
只是一个打印对象的函数。所以它适用于String
和Integer
类型。
如果ifPresent
只使用了Consumer<T>
,就不能像上面那样编写代码,因为不能Consumer<Object>
在需要的地方Consumer<String>
或Consumer<Integer>
需要的地方使用。但是在消费者实例已经存在并且与多种T
类型兼容的情况下,Consumer<? super T>
可以重用消费者实例。
归档时间: |
|
查看次数: |
37 次 |
最近记录: |