有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的返回类型奇怪行为

这是一位朋友问的。奇怪的是,这段java代码可以正确编译和运行

int getArray() [] { ... }

我是不是遗漏了什么。难道不是吗

int[] getArray() { ... }

编辑: getArray()在这里是一个返回整数数组的函数


共 (3) 个答案

  1. # 1 楼答案

    section 8.4 of the JLS

    For compatibility with older versions of the Java SE platform, the declaration of a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the formal parameter list. This is supported by the following obsolescent production, but should not be used in new code.

    虽然我偶尔看到一个在名称(ick)后面带有数组说明符的变量声明,但我从未看到它用于这样的方法声明。奇怪

  2. # 3 楼答案

    根据Java语言规范第§10.2节,声明数组的两个语法在Java中是等效的:

    int[] array;
    int array[];
    

    正如Jon Skeet在回答中引用的JSL第§8.4节所述,同样的情况也适用于方法的返回类型

    int[] getArray() { ... }
    int getArray()[] { ... }