I’m something of a newbie with Java and I’m trying to learn how to use generics. Can anyone explain to me what’s wrong with this code?
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 Error: The method which(T, Collection<T>) in the type Generics is not applicable for the arguments (Integer, Integer[]).
Granted, I could just use int c = Arrays.binarySearch(b, a) in this particular case (sorted, comparable elements) instead of the custom method which, but this is a learning exercise.
Can anyone explain what I’m misunderstanding here?
An array is not a Collection
try
And, as Yanflea points, this change implies that (other optimizations added)