gpt4 book ai didi

没有引用的Java数组传递

转载 作者:搜寻专家 更新时间:2023-11-01 01:08:26 26 4
gpt4 key购买 nike

我试图在不使用引用的情况下传递数组,而是直接使用值:

    public static void main(String[] args){
int[] result = insertionSort({10,3,4,12,2});
}

public static int[] insertionSort(int[] arr){
return arr;
}

但它返回以下异常:

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

当我尝试下面的代码时,它起作用了,任何人都可以解释原因吗?

    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;
}

最佳答案

必须是

int[] result = insertionSort(new int[]{10,3,4,12,2});

{10,3,4,12,2} 是数组初始化的语法糖,必须和下面的声明语句一起使用-

int[] arr = {10,3,4,12,2};

下面的东西也是不允许的-

int[] arr; // already declared here but not initialized yet
arr = {10,3,4,12,2}; // not a declaration statement so not allowed

关于没有引用的Java数组传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com