怪阵返回类型 [英] Strange array return type

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

问题描述

已经看到了阵列任何一个[] 放在这样的方法签名后?

 公共静态字符串mySplit(String s)将[] {
    返回s.split(,);
}公共静态无效的主要(字符串参数... args){
    的String []字= mySplit(A,B,C,D,E);
    的System.out.println(Arrays.toString(字));
}

打印

  [A,B,C,D,E]

在过去,奇怪的符号已经为C的兼容性,但我无法想象有人用C要么写的。

有谁知道这是为什么,甚至允许?

我使用的Java 7更新10,如果它很重要。

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


BTW,这并不编译,我也不会指望它

 公共静态< T>清单mySplit(String s)将< T> {
    返回Collections.emptyList();
}


解决方案

  

有谁知道这是为什么,甚至允许?


在这种情况下,它是与Java本身的向后兼容性。从 JLS 8.4节


  

为了与旧版本的Java SE平台的兼容性,返回数组的方法的声明被允许放置(部分或全部),正式参数列表之后形成数组类型的声明空支架对。这是通过以下过时生产的支持,但不应该在新code可以使用


是的,你确实应当把它作为具有比冲击其他开发商没有其他好的目的所憎恶的。其实,你也许可以打赌用它在派对赢了一些钱,这将编译,对谁从来没有见过这人......

下面是其中正义感codeRS期望是无效的一种方法:

 公共字符串[] mwahahaha(字符串[]邪恶[])[] {
    以怨报德;
}

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

prints

[a, b, c, d, e]

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?

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

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?

In this case it's for backward compatibility with Java itself. From the 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.

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天全站免登陆