奇怪的数组返回类型 [英] Strange array return type

查看:25
本文介绍了奇怪的数组返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Has any one seen the array [] placed after the method signature like this?

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 来写这个.

In the past, odd notations have been for "C" compatibility, but I wouldn't imagine someone writing this in C either.

有谁知道为什么这是允许的?

Does anyone know why this is even allowed?

我使用的是 Java 7 update 10,以防万一.

I am using Java 7 update 10, in case it matters.

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

This does the same thing in Java 6. http://ideone.com/91rZV1

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

BTW this doesn't compile, nor would I expect it to

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

推荐答案

有人知道为什么允许这样做吗?

Does anyone know why this is even allowed?

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

In this case it's for backward compatibility with Java itself. From the JLS section 8.4:

为了与旧版本的 Java SE 平台兼容,返回数组的方法的声明允许在形参列表之后放置(部分或全部)形成数组类型声明的空括号对.以下过时产品支持此功能,但不应在新代码中使用.

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.

是的,您确实应该将其视为可憎之物,除了震惊其他开发人员之外没有任何其他好处.实际上,您可能可以通过打赌它会编译来用它在聚会上赢一些钱,而不是那些从未见过它的人......

And yes, you should indeed regard it as an abomination which has no good purpose other than to shock other developers. Actually, you might be able to use it to win some money at parties by betting that it would compile, against folks who've never seen it...

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

Here's the kind of method which right-minded coders would expect to be invalid:

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

这篇关于奇怪的数组返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆