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

You can simply replace which(a, b) in your code with which(a, Arrays.asList(b)). Arrays.asList is a simply adapter that gets an array (of reference types) to conform to be viewed as a List; which allows you to use any method that is written for Lists easily on an array (excluding arrays of primitives).

于 2012-06-05T19:09:58.587 回答