不完全是。
Function<? super T, U> 与 Function<? super T, ? extends U> 不同。
例如,即使我将Function<Object, String> 传递给该方法,我仍然可以获得Optional<CharSequence>。如果方法被定义为<U> Optional<U> map(Function<? super T, U> mapper),那么这是不可能的。
这是因为泛型是不变的:<T> 与 <? extends T> 不同。这是用 Java 语言实现的设计决策。
让我们看看Jon Skeet explains what would happen如果泛型不是不变的:
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
public void ouch() {
List<Dog> dogs = Arrays.asList(new Dog(), new Dog());
List<Animal> animals;
// This would be legal, right? Because a list of dogs is a list of animals.
List<Animal> animals = dogs;
// This would be legal, right? Because a cat could be added to a
// list of animals, because a cat is an animal.
animals.add(new Cat());
// Unfortunately, we have a confused cat.
}
虽然我不完全确定您在 cmets 中的意思,但我会尝试详细说明。
如果您可以完全控制您提供的Function,那么无论方法的签名是Function<? super T, U> 还是Function<? super T, ? extends U>,您只需相应地调整您的Function。但该方法的作者可能希望该方法尽可能灵活,允许提供Function,其第二个参数也是U 的子类,而不仅仅是@ 987654341@ 本身。实际上,您将其下限从U 扩大到U 的某个子类型。
所以函数应该真的读作<U> Optional<? the-most-general-but-fixed-supertype-of U> map(Function<? super T, U> mapper),但这样表达会很尴尬。
我确实会很尴尬。此外,您提出的符号与map() 的实际方法签名之间存在差异,这涉及下限和上限的含义。
阅读更多: