Syntactic sugar and Java arrays.
2 Comments Published January 8th, 2010 in Java Tags: Java, Opinion.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.”
Leave a Reply
Search
Calendar
| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Dec | Apr » | |||||
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Archives
Categories
Tag Cloud
Android API Bash Bios CSS Development Eclipse Encription Error Handling Font Git Google GWT Hardware How-To HTML Installation iPod Java JavaScript Karmic Linux Lucks MacBook Open Source Opinion OSX Pitfalls Pkg Practices Python Resume Security Software Suspend TDD Testing Tools Top Down Tricks Ubuntu Uninstall Wakup On Lan Web Workaround
WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.
Blog License
Blogs I like
Books on the desk
Friends' Blogs
- Antonio Terreno & Valter Bernardini
- Bruno Bossola
- Daniele Galluccio
- Domenico Ventura
- Ed Schepis
- Fabrizio Gianneschi
- Luca Grulla
- Luigi Zanderighi
- Marcello Teodori
- Mida Boghetich
- Muralidharan Chandrasekaran
- Piero Ricca
- Renzo Borgatti
- Simone Bordet
- Simone Bruno
- Uberto Barbini
- Valvolog
- Webtide blogs (Greg Wilkins & Jan Bartel)
Links





















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