Syntactic sugar and Java arrays.

Recently I got surprised by following case.

In Java you can declare an array in following valid ways:

String[] strings = new String[] { "foo", "bar" };
// the above is equivalent to the following:
String[] strings = { "foo", "bar" };

So following Java code is perfectly valid:

public class Foo {

    public void doSomething(String[] arg) {}

    public void example() {
        String[] strings = { "foo", "bar" };
        doSomething(strings);
    }

}

Is there any valid reason why, instead, the following code shouldn't be valid?


public class Foo {

    public void doSomething(String[] arg) {}

    public void example() {
        doSomething({ "foo", "bar" });
    }

}

I think, that the above syntax would have been a valid substitute to the varargs introduced in Java 5. And, more coherent with the previously allowed array declarations.


2 Responses to “Syntactic sugar and Java arrays.”  

  1. 1 jan

    sure it is not valid…try the following:
    doSomething(new String[] {“foo”,”bar”});

    why should he know it’s a string array in the first place? ok it’s defined by the method doSomething…but how should he know, that what you are giving in is really such a type :)

  2. 2 Luigi

    I am just saying that there’s no logical reason why that shouldn’t compile.

    >why should he know it’s a string array in the first place?
    > …
    >but how should he know, that what you are giving in is really such a type

    exactly as the compiler does for the assignation (without needing any cast):

    String[] strings = { “foo”, “bar” };

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Calendar

January 2010
M T W T F S S
« Dec   Apr »
 123
45678910
11121314151617
18192021222324
25262728293031

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:

Archives


Categories

Tag Cloud


Listening