2016-02-12 8 views

答えて

4

問題はジェネリックスがどのように機能するかにあります。具体的にはGenericsは非正規化です...つまり、定数がMyInterfaceのサブクラスであっても、Iterable<enum.Constants>Iterable<enum.MyInterface>と表示されません。

しかし、それを回避する方法があります:Generic wildcards

static void accept(Iterable<MyInterface> values)static void accept(Iterable<? extends MyInterface> values)に変更すると、になります。

+0

それは実際に動作します。それではすぐに回答を受け付けます。どうもありがとう! – tannerli

0

一般的なタイプはこのように継承されませんが、一見したところ直感に反して見えるかもしれません。 Iterable<? extends MyInterface>を使用すると、(たとえば、)のタイプの、MyInterface(たとえば、Constants)のいずれかを使用できるようになります。

2

ConstantsMyInterfaceのサブタイプであるにも関わらず、Iterable<Constants>Iterable<MyInterface>のサブタイプではないので、あなたがIterable<? extends MyInterface>代わりのIterable<MyInterface>を使用する必要がある - と私はあなたの理由を紹介します:それはそうだった場合のは、使用してみましょう(

List次の例ではIterableの代わりに)、私はこれを行うことができます:

List<Constant> constantsList = new ArrayList<Constants>(); // list of constants 
List<MyInterface> ifaceList = constantsList; // you said this would be OK ... 
// assume MyOtherImplementation is another implmentation of MyInterface 
ifaceList.add(new MyOtherImplementation()); // OK, MyOtherImplementation implements MyInterface 
Constant myConst = constantsList.get(0); // Oops! I just got an instance of MyOtherImplementation from List<Constant> - not cool. 
関連する問題