n00*_*13f 1 java arrays declaration
/**
* 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 reasons?
processNames({ "Jane", "John" });
// fails, but i thought Java 5 [vargs][1] handles this
processNames("Jane", "John");
}
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)processNames({ "Jane", "John" });这失败了,为什么,有什么理由吗?
您没有指定类型.Java不在这里做类型推断; 它希望您指定这是一个字符串数组.这个问题的答案也可能对此有所帮助
Run Code Online (Sandbox Code Playgroud)processNames("Jane", "John");这也失败了,但我认为Java 5 varargs处理这个问题
如果你想要varargs,那么你应该这样编写你的方法:
public void processNames(String... arg)
Run Code Online (Sandbox Code Playgroud)
请注意...而不是[].只接受一个数组并不能让你在该方法上使用varargs.