1

私はJavaの初心者で、ジェネリックの使用方法を学ぼうとしています。このコードの何が問題なのか、誰か説明してもらえますか?

import java.util.Collection;
import java.util.Iterator;

public class Generics {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Integer a = new Integer(28);

        Integer[] b = {2, 4, 8, 16, 20, 28, 34, 57, 98, 139}; 
            //I'd prefer int[], but understand native types don't go with generics

        int c = which(a, b); // <--- error here, see below

        System.out.println("int: "+ c);
    }

    static <T extends Number> int which( T a, Collection<T> b) {
        int match = -1;
        int j = 0;
        for (Iterator<T> itr = b.iterator(); itr.hasNext();) {
            T t = (T) itr.next();
             if (a == t) {
                 match = j; 
                 break; 
             }
             j++;
        }
        return match;
    }
}

エラー: The method which(T, Collection<T>) in the type Generics is not applicable for the arguments (Integer, Integer[])

確かにint c = Arrays.binarySearch(b, a)、カスタム メソッドの代わりにこの特定のケース (並べ替えられた比較可能な要素) を使用することもできますwhichが、これは学習課題です。

ここで私が誤解していることを誰かが説明できますか?

4

3 に答える 3

5

配列はコレクションではありません

試す

static <T extends Number> int which( T a, T[] b) {

そして、Yanflea が指摘するように、この変更は (他の最適化が追加されたことを意味します)

int j = 0;
for(T t : b) {
  if (a.equals(t)) {
    return j;
  }
  j++;
}
return -1;
于 2012-06-05T15:02:48.720 に答える
4

交換

Integer[] b = {2, 4, 8, 16, 20, 28, 34, 57, 98, 139}

List<Integer> b = Arrays.asList(2, 4, 8, 16, 20, 28, 34, 57, 98, 139);
于 2012-06-05T15:07:34.283 に答える
0

which(a, b)コードを に置き換えるだけですwhich(a, Arrays.asList(b))Arrays.asListとして表示されるように準拠する (参照型の) 配列を取得する単純なアダプターListです。これにより、s 用に記述された任意のメソッドをList配列 (プリミティブの配列を除く) で簡単に使用できます。

于 2012-06-05T19:09:58.587 に答える