• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Gotcha: Varargs spoofs method signature [from Sierra/Bates book]

 
Steven Elliott
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The subject line is the best I could do to describe something that caught me out in the first series of self-tests, question 3 in the SCJP Sierra/Bates book.

Given:


So you have the same method called with two different method signatures.
The test question is:
Which, inserted independently at line 6, will compile? (Choose all that apply.)
A. static void doStuff(int... doArgs) { }
B. static void doStuff(int[] doArgs) { }
C. static void doStuff(int doArgs...) { }
D. static void doStuff(int... doArgs, int y) { }
E. static void doStuff(int x, int... doArgs) { }

I answered A as the only correct answer and was surprised to find that E also is correct! The reason I didn't pick E was in the first case, doStuff(1), would not compile because it would be missing the varargs argument (there is only one argument, 1, after all). Surprisingly, though, not only does the code compile but it runs.

Can someone enlighten me why doStuff(1) (w/one argument) will compile and run with E which requires two arguments?
 
Stephan van Hulst
Bartender
Pie
Posts: 4826
34
Chrome Netbeans IDE Windows
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A vararg parameter can take any amount of arguments, even zero.

Not only does the method foo(int... values) allow the method call foo(1), it will even allow the method call foo(), in which case values will hold an empty array.
 
Paul Clapham
Sheriff
Pie
Posts: 20169
24
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a general high-level rule related to the design of the Java language, which can be stated roughly as "We don't need no stinkin' special cases".

So in this case that rule says "There can be any number of parameters for a vararg. Does that mean any number higher than 1? No, that would make 0 and 1 be special cases. We don't need that. Just any number."

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic