ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Creating Varargs in Java 1.5 Tiger
Subject:   Are varargs an improvement?
Date:   2004-08-14 20:30:22
From:   MarcinJeske
I have read a number of articles and comments lauding varargs as one of the best new features in 1.5. I don't get it. They just seem to be a slight change of syntax and a change to coding style. Further, while they save some people a bit of typing, they introduce potentially elusive bugs (as noted in the excerpt).


I've never had a problem with supplying multiple arguments to a method in Java... I just use an array (hmmm... sort of like Java 1.5 does). So all varargs does is replace the [] with a NEW, SEMANTICALLY EQUIVALENT symbol, the ..., and save some typing for the method's clients:


foo(one, two, three)
instead of:
foo(new Object [] {one,two,three)


Worse yet, you have to remember to typecast arrays passed to vararg methods to avoid them being treated as the argument list... unless that's what you want.


Further, as opposed to explicitly using arrays, varargs can be used only once in the parameter list, at the end. (Also, I think the author alluded to another problem in the excerpt:
void foo(String x, String... list) {}
void foo(String x, String y, String... list) {}
foo("a","b","c");
where it is unclear which method to match and the compiler will return an awkward error. Using arrays would avoid this ambiguity.)


Also, using varargs could degrade coding style... and lead to mistakes which would have been caught as type errors using arrays.


Ex:
void sendMail( Person sender, Person... recievers);


sendMail( myself, reciever1, receiver2 );
sendMail( recevier1, recevier2 );


Both of those method invocation will compile and work, but one of them won't do the right thing (because we forgot the "sender" argument). The mistake would have been caught by the type system if the method had been defined as:


void sendMail( Person sender, Person [] receviers );
sendMail( myself, new Person [] {receiver1, receiver2} );


Finally, I want to say that I liked the style of the book, and am considering buying it... however, the editors might like to fix the manuscript up for the next printing, because at least in the excerpt, there are a number of places where the code doesn't seem to match the output, or where the '-' is used when a "=" should have been.


Best,
Marcin


1 to 2 of 2
  1. Are varargs an improvement?
    2005-01-11 01:34:11  Krishnas [View]

    • Are varargs an improvement?
      2006-02-04 19:02:20  bastos [View]

  2. Brett McLaughlin photo Are varargs an improvement?
    2004-08-19 06:36:52  Brett McLaughlin | O'Reilly AuthorO'Reilly Blogger [View]

    • Are varargs an improvement?
      2004-10-08 15:55:03  MarcinJeske [View]

1 to 2 of 2