English 中文(简体)
未汇编的通用方法为何?
原标题:Bounded generic method not compiling - why?

下面的法典对我来说是完全有意义的,因为它增加了某种类型的要素,即T类和S类的超级类型,这肯定是一种超级类型,因此汇编者拒绝在收集中增加内容?

class GenericType<S,T extends S>{
   void add1(Collection<? super T> col ,S element ){
        col.add(element);  // error
       // The method add(capture#9-of ? super T) in the type 
       // Collection<capture#9-of ? super T> is not applicable for the arguments (S)
    }
}
最佳回答

<代码>Collection<? 超级T> do not系指“可包含<代码>T<>/code>和任何超级类别”的收集—实际上不可能提出这一限制。 它指的是“只能包含某些特定类别,即<代码>T的超级类别”的收集——基本上确保你能够添加<代码>T。

The method can be called with a Collection<T>, yet you want to add an S to it.

问题回答

Thake an example, if A <- B <- C where <- means that is the supertype, then if S = B and T = C you cannot add an instance of S to a collection of T.

<代码>超级型号 T可以是<代码>另一类超级体的超级类型或亚类。 T (此处为<代码>S)。

new GenericType<Object,Integer>().add1(new ArrayList<Integer>(), "");

You are trying to put an element of type S into a collection of type T. Generics aren t polymorphic. You have to take notice of 2 problems here. you are trying to create an Collection of type concreteObject extends Object and are adding an object So when you have

Car extends Vehicle{}
ElectricCar extends Car{}

你正在努力这样做。

Collection<? extends Car> collection;
collection.add(new Vehicle());

第二个问题是非吗? 见这一重大解释——和;。 清单与否;Dog> 清单与设计的子类;Animal>? 为什么 Java是含蓄的多吗?





相关问题
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 ...

热门标签