Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

java - Strange array return type

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...