2016-11-30 7 views
2

次のコードが動作する理由を私は理解していない:addToCollection(T [] a、Collection <T> c)の型Tは同じではないでしょうか?

import java.util.ArrayList; 
import java.util.Collection; 

    public class Main { 

     public static void main(String[] args) { 
      Integer[] arr=new Integer[]{1,2,3}; 
      ArrayList<Object> al=new ArrayList<>(); 
      addToCollection(arr, al); 
     } 
     static <T> void addToCollection(T[] a, Collection<T> c) 
     { 
      for(T o:a) 
       c.add(o); 
     } 
    } 

は、それはすべきではない:

...

static <T> void addToCollection(T[] a, Collection<? super T> c) 

を...?

通話中にタイプTが同じであってはなりませんか?

コメントの中で述べたように、私の質問は「どのタイプがTに推論されるか」です。コードが動作しているので、階層の「上位」型が推測されると仮定します。

+0

同じものは何ですか? – shmosel

+0

あなたが 'Bicycle'の配列を持っているならば、' Vehicle'のコレクションにそれを加えることはできませんか? – chrylis

+3

彼は 'ArrayList 'と 'Integer []'をなぜ渡すことが許されているのか聞いています。問題は 'T'のために推論される型であり、' Object'だと思っていますが、現時点ではJLSに対する具体的な参照はありません。 –

答えて

2

arralはどちらもObjectのサブタイプですaddToCollection関数を戻り値の型に変更すると、次のようになります。

public static class Main { 

    public static void main(String[] args) { 
     Integer[] arr=new Integer[]{1,2,3}; 
     ArrayList<Object> al=new ArrayList<>(); 
     Collection<Object> objects = addToCollection(arr, al); // Compiles 
     Collection<Integer> numbers = addToCollection(arr, al); // Doesn't compile 
    } 

    static <T> Collection<T> addToCollection(T[] a, Collection<T> c) 
    { 
     for(T o:a) // Behold the side effect 
      c.add(o); 

     return c; 
    } 
} 
+0

したがって、2番目の 'addToCollection(arr、al)'は 'Collection 'を返します。 – Christian

+0

型が正しくないため、はい、コンパイルされません。それはそれを示すだけです。 – Roger

関連する問題