我有一个两部分的问题



我不知道这意味着什么。这是什么意思?

另外,对通配符类型(无界和有界)有哪些限制?例如,如果我有对MyClass<?>MyClass<? extends SomeOtherClass>的引用,则不允许通过该引用调用哪些方法。我不了解通配符允许或不允许我执行,这可能是为什么我不理解本书中引用的原因。

我有第二部分的示例:

class SomeOtherClass
{
[...]
}

class MyClass<T>
{
[...]
}

class Test
{
     public static void main(String[] arg)
     {
         MyClass<? extends SomeOtherClass> myClass = new MyClass<String>() // for instance what does the wild card reference limit me to in any way. In a general sence.
     }
}

最佳答案

对于返回参数化类型的对象的集合和类,通配符界限(上下限)通常是必需的。

您经常会听到有关PECS的信息,这意味着“生产者扩展,消费者 super ”。我建议您阅读the answer to this question,以避免重复答案。

  • 更准确地说,当您使用<? extends TheClass>定义通配符时,您将告诉编译器通配符对象至少为TheClass类型。因此,您可以像TheClass的实例一样使用此对象,并调用此类型建议的任何方法。
  • 现在,当您将通配符定义为<? super TheClass>时,您将告诉编译器通配符对象类型是由TheClass类型实现或扩展的。这意味着对象类型可能不是TheClass,但是TheClass对象可以用作通配引用的实例。因此,您不能在该对象上调用任何东西,因为它的类型仅在运行时才知道,但是您可以将该对象传递给等待通配符的对象的方法。

  • 例子:
    private void foo(List<?> list) {
        Object o = list.get(0); // ok
        list.add(new Object()); // won't compile!
    
        // you cannot add anything, and only extract Object instances
    }
    
    private void foo(List<? extends TheClass> list) {
        Object o1 = list.get(0);   // ok
        TheClass o2 = list.get(0); // ok
        list.add(new Object());    // won't compile!
        list.add(new TheClass());  // won't compile!
    
        // You are sure that the objects are of a subtype of TheClass,
        // so you can extract TheClass instances safely. However, you cannot
        // add anything to this list since its type is not known (may be
        // different from TheClass, so the compiler does not allow anything).
    }
    
    private void foo(List<? super TheClass> list) {
        Object o1 = list.get(0);   // ok
        TheClass o2 = list.get(0); // won't compile!
        list.add(new Object());    // won't compile!
        list.add(new TheClass());  // ok
    
        // You are sure that the objects are of a type implemented by TheClass,
        // so you can add any TheClass instances to the list. However, you cannot
        // extract TheClass objects since the objects type may be just implemented
        // by TheClass, but different.
    }
    

    10-07 22:06