English 中文(简体)
为什么我会把T类的物体转至某种类型的物体上? ?
原标题:Why can t I pass an object of type T to a method on an object of type <? extends T>?

在 Java,假定我有以下舱面集装箱,其中含有一个舱面物品清单:


    public class Container<T>
    {
        private List<Item<? extends T>> items;

        private T value;

        public Container(T value)
        {
            this.value = value;
        }

        public void addItem(Item<? extends T> item)
        {
            items.add(item);
        }

        public void doActions()
        {
            for (Item<? extends T> item : items)
            {
                item.doAction(value);
            }
        }
    }

    public abstract class Item<T>
    {
        public abstract void doAction(T item);
    }

Eclipse gives the error: The method doAction(capture#1-of ? extends T) in the type Item is not applicable for the arguments (T)

我早就阅读了通用例子和前后的各种张贴,但我仍然可以说明为什么允许这样做。 单单还未在其拟议的固定点中提供任何帮助。 变式<代码> 是T类,为何不适用<代码>? 延伸 T?

最佳回答

研究以下方案:

public class Cell<T> { 
  private T value;

  public void set(T t) { value = t; }
  public T get() { return value; }
}


Cell<Integer> ci = new Cell<Integer>();
Cell<? extends Number> cn = ci;

cn.set(new Double(5.0));  // (A) <-- Compile error here


Integer n = ci.get(); // (B) Runtime error!  

如你所说,(A)项没有汇编。 如果这一条系合法的话,则在操作时间,方案将通过<条码>Double<>/code>对<条码>cn.set(>的电动类型<条码>/代码>;Integer>。

在随后交付(B)时,ci.get()将退回(A)----were. Declaration of ci。 说到,其<代码>get()方法得到保证,可以返回。 Integer。 为了防止这种混淆(实际上打破了认证程序强有力的打字理论),汇编者从<代码>T到<不等; 延伸 T>

问题回答

PECS - Productioner-extends, Consumer-super

将<代码>extends改为super在您的声明中(包括你在行文中省略的条目),并汇编:

my(只有!) blog post。 它没有直接谈论“? 延伸T”案件,但任何地方都看着“吗?” 目的延伸”,应当明确。

基本上,你拿着一份“一些延伸T”的清单,但你不知道什么时候汇编了。

约束被逆转。 项目<X>可动用X或X级作为其行动。 现在,<代码>。 延伸 T是指X为T级。 因此,你将T转至一个预期X的物品,即T级,而不是T级。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签