Why shall I explicitly cast null for the invocation of a varargs method?
I've got the following code:
public static void varargsMethod(String ... strings) {
if (strings != null && strings.length != 0) {
for (String s : strings) {
System.out.println(s);
}
} else {
System.out.println("Hello (string free) world!");
}
}
public static void main(String[] args) {
varargsMethod(null);
varargsMethod((String[]) null);
varargsMethod((String) null);
varargsMethod();
}
I wonder why the first invocation with null as the argument generates a
warning with the hint, that an explicit cast is needed. From the answers
on this question it is not clear for me, why this cast is needed. The
first two invocations work and produce the same result, while the third
produces "null". I explicitly want the behaviour of the first two
invocations.
Shouldn't null be always valid (and automatically casted) for reference
types and arrays? I don't see, why the type information is important in
this case.
No comments:
Post a Comment