Say i have some method header..
public static <E> void myMethodName(E[], Comparator<E> comparator).
Why would I get a type error when attempting to call:
myMethodName(int[],
new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) { return e1 - e2; }
}
);
any ideas?
First, let's look at a few things.
You have a generic method (it's missing a variable though, but I'll overlook that) which requires a generic type. Java infers, based on the fact that your array is of type int
, that the method is type bound to Integer
.
You have a primitive int[]
, which you are providing as the first argument. In the formal signature, it is type bound to Integer
.
The problem here: an int[]
is not equivalent to an Integer[]
. They are two completely different objects (since they're both arrays as opposed to objects that can be autoboxed).
The proper way to avoid the issue is to use an Integer[]
instead. The elements that you place inside the array will be autoboxed according to the rules of autoboxing and conversion, though.
尽管自动装箱可能会使问题感到困惑,但int
和Integer
不是同一类型。
@user2574476 : you can point E
to any reference type not primitive type. So instead of using int[], you should use Integer[].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.