java - 奇怪的数组返回类型

标签 java arrays syntax declaration

有没有人见过像这样放在方法签名之后的数组[]

public static String mySplit(String s)[] {
    return s.split(",");
}

public static void main(String... args) {
    String[] words = mySplit("a,b,c,d,e");
    System.out.println(Arrays.toString(words));
}

打印

[a, b, c, d, e]

过去,“C”兼容性的奇怪符号一直存在,但我也无法想象有人用 C 编写此代码。

有谁知道为什么甚至允许这样做?

我正在使用 Java 7 update 10,以防万一。

这在 Java 6 中做同样的事情。http://ideone.com/91rZV1


顺便说一句,这不会编译,我也不希望它编译

public static <T> List mySplit(String s)<T> {
    return Collections.emptyList();
}

最佳答案

Does anyone know why this is even allowed?

在这种情况下,它是为了向后兼容 Java 本身。来自 JLS section 8.4 :

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.

是的,您确实应该将其视为可憎之物,除了震惊其他开发人员之外没有其他任何目的。实际上,你可以用它在聚会上赢一些钱,赌它会编译,对抗那些从未见过它的人......

以下是正确的编码人员认为无效的方法:

public String[] mwahahaha(String[] evil[])[] {
    return evil;
}

关于java - 奇怪的数组返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14203298/

相关文章:

java - 为什么我的代码使用监听器将值设置为错误的 View

java - 使用Javamail获取附件

java - java中的CMD.exe命令没有终止

android - "if"工作不正常

javascript - 'var foo = function ...' 和 'function foo() ...' 之间的区别

bash - AWK数组语法错误(意外的换行符或字符串结尾)

java - 如何在 Java 中的字符串上使用 Comparable CompareTo

javascript - 如何将嵌套的对象数组转换为数组对象

c - 嘿有人可以帮我完成这个 C 作业吗

ruby - Ruby 1.9 中新的散列语法有什么好处?