Working with Java arrays
/**
* Testing Arrays
* @author N002213F
* @version 1.0
*/
public class JavaArrays {
public void processNames(String[] arg) {
//-- patented method, stop, do not read ;)
}
public void test() {
// works fine
String[] names1 = new String[] { "Jane", "John" };
processNames(names1);
// works fine, nothing here
String[] names2 = { "Jane", "John" };
processNames(names2);
// works again, please procced
processNames(new String[] { "Jane", "John" });
// fails, why, are there any r开发者_Go百科easons?
processNames({ "Jane", "John" });
// fails, but i thought Java 5 [vargs][1] handles this
processNames("Jane", "John");
}
}
processNames({ "Jane", "John" });
This fails, why, are there any reasons?
You didn't specify a type. Java doesn't do type inference here; it expects you to specify that this is a string array. The answers to this question may help for this, too
processNames("Jane", "John");
This fails too, but I thought Java 5 varargs handles this
If you want varargs, then you should write your method as such:
public void processNames(String... arg)
Note the ...
instead of []
. Just accepting an array doesn't entitle you to use varargs on that method.
On your last line : processNames(String ...args);
would have to be written like this for varargs to work.
The third call is incorrect because you cannot create an array like that, you do it like you do in the second call. If you want the final call to succeed you must declare processNames as being a receiver of varargs (see here)
精彩评论