为什么谓词&lt ;?超级SomeClass>不适用于对象? [英] Why is Predicate<? super SomeClass> not applicable to Object?

查看:125
本文介绍了为什么谓词&lt ;?超级SomeClass>不适用于对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个谓词为Predicate<? super SomeClass>的谓词.我天真地希望它适用于层次结构中所有SomeClass的超类,包括Object.

Assume we have a predicate declared as Predicate<? super SomeClass>. I would naively expect it to be applicable to any superclass of SomeClass up the hierarchy, including Object.

但是,该谓词不适用于Object.我收到以下错误:

However this predicate is not applicable to Object. I get the following error:

谓词类型的方法test(capture#3-of Some SomeClass的方法)不适用于参数(Object)

The method test(capture#3-of ? super SomeClass) in the type Predicate is not applicable for the arguments (Object)

演示.

为什么Predicate<? super SomeClass>不适用于Object的实例?

Why is Predicate<? super SomeClass> not applicable to an instance of Object?

代码:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.net.URL;
import java.util.function.Predicate;


/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Predicate<? super URL> p = u -> u.getFile().isEmpty();
        p.test(new Object());
    }
}

推荐答案

对于Predicate<? super SomeClass>变量,您可以分配Predicate<SomeClass>实例或Predicate<Object>实例.

For a Predicate<? super SomeClass> variable, you can assign a Predicate<SomeClass> instance, or a Predicate<Object> instance.

但是,您不能将Object传递给Predicate<SomeClass>test()方法.您只能传递SomeClass实例.

However, you can't pass an Object to the test() method of a Predicate<SomeClass>. You can only pass a SomeClass instance.

因此,您不能将Object传递给Predicate<? super SomeClass>

Therefore you can't pass an Object to the test() method of a Predicate<? super SomeClass>

请考虑以下内容:

Predicate<URL> p1 = u -> u.getFile().isEmpty();
Predicate<? super URL> p2 = p1;

p2指的是Predicate<URL>,因此您不能将new Object()传递给其test()方法.

p2 is referring to a Predicate<URL>, so you can't pass a new Object() to its test() method.

换句话说,为了使p.test(new Object())被编译器接受,它对于可分配给Predicate<? super URL> p变量的任何 Predicate必须有效.由于可以将Predicate<URL> Predicate分配给该变量,并且其test()方法无法接受Object,因此编译器无法接受p.test(new Object()).

In other words, in order for p.test(new Object()) to be accepted by the compiler, it must be valid for any Predicate that can be assigned to the Predicate<? super URL> p variable. Since the Predicate<URL> Predicate can be assigned to that variable, and its test() method cannot accept an Object, p.test(new Object()) cannot be accepted by the compiler.

顺便说一句,在您的特定示例中,您正在创建Predicate<URL>,而URL是最终课程.因此,您只需将其声明为:

BTW, in your specific example, you are creating a Predicate<URL>, and URL is a final class. Therefore, you should simply declare it as:

Predicate<URL> p = u -> u.getFile().isEmpty();

没有理由使用? super? extends.

这篇关于为什么谓词&lt ;?超级SomeClass&gt;不适用于对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆