5

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

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

4 回答 4

10

它一定要是

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
于 2012-09-30T18:08:51.550 回答
5
insertionSort({10,3,4,12,2})

不是有效的 java,因为您没有在方法调用中指定类型。JVM 不知道这是什么类型的数组。它是具有 double 值还是具有 int 值的数组?

你能做的是insertionSort(new int[]{10, 3 ,4 12, 2});

于 2012-09-30T18:11:19.493 回答
1

int[] array = { a, b, ...., n }是一个速记初始化 - 你必须写:

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

匿名初始化它。

于 2012-09-30T18:10:06.513 回答
1

没有什么可以补充其他人的话。

但是我相信你应该使用new int[]{10,3,4,12,2}(就像其他人所说的那样)并且 Java 不允许你使用的原因只是{10,3,4,12,2}Java 是强类型的。

如果您只是使用{10,3,4,12,2},则不知道数组元素的类型是什么。它们似乎是整数,但它们可以是int, long, float, double, 等等...

好吧,实际上它可能会从方法签名中推断出类型,如果不合适就会引发编译错误,但这似乎很复杂。

于 2012-09-30T18:13:43.093 回答