Ari*_*deh 4 java arrays reference
我试图传递一个数组而不使用引用,但直接使用值:
public static void main(String[] args){
int[] result = insertionSort({10,3,4,12,2});
}
public static int[] insertionSort(int[] arr){
return arr;
}
Run Code Online (Sandbox Code Playgroud)
但它返回以下异常:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token ")", delete this token
Run Code Online (Sandbox Code Playgroud)
当我尝试以下代码时,它可以工作,有人可以解释原因吗?
public static void main(String[] args){
int[] arr = {10,3,4,12,2};
int[] result = insertionSort(arr);
}
public static int[] insertionSort(int[] arr){
return arr;
}
Run Code Online (Sandbox Code Playgroud)
它一定要是
int[] result = insertionSort(new int[]{10,3,4,12,2});
Run Code Online (Sandbox Code Playgroud)
{10,3,4,12,2} 是一个用于数组初始化的语法糖,它必须与声明语句一样,如下所示 -
int[] arr = {10,3,4,12,2};
Run Code Online (Sandbox Code Playgroud)
以下内容也是不允许的 -
int[] arr; // already declared here but not initialized yet
arr = {10,3,4,12,2}; // not a declaration statement so not allowed
Run Code Online (Sandbox Code Playgroud)
insertionSort({10,3,4,12,2})
Run Code Online (Sandbox Code Playgroud)
是无效的java,因为您没有在方法调用中指定类型.JVM不知道这是什么类型的数组.它是一个具有double值或int值的数组吗?
你能做的是 insertionSort(new int[]{10, 3 ,4 12, 2});