我是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
,但这是一个学习练习。
任何人都可以解释我在这里的误解吗?
答案 0 :(得分:5)
数组不是Collection
试
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;
答案 1 :(得分: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);
答案 2 :(得分:0)
您只需使用which(a, b)
替换代码中的which(a, Arrays.asList(b))
即可。 Arrays.asList
是一个简单的适配器,它获取一个数组(引用类型)以符合被视为List
;它允许您在数组上使用为List
编写的任何方法(不包括基元数组)。