• Post Reply Bookmark Topic Watch Topic
  • New Topic

var-args VS array  RSS feed

 
Hardik Trivedi
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all Genius people out there...

I just come across with var-args i.e. Variable arguments..
I understand the functionality and feel that it works same as array does.Then

CAN anyone tell me why we should use it.. i.e. Pros and cons of it...
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it works well in string formatting. Something like:



Of course you could pack the arguments into an array, which is in fact what Java did for a long time before var-args were introduced, but it's simpler and more readable this way.

 
Tim McGuire
Ranch Hand
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
behind the scenes, java is actually making an array of your arguments and passing it when you use var args, so it truly is the same.

Pros: easier to code. You don't have to have code to construct the array you pass.
Cons: unexpected consequences. used wrong, they can strip away some of the type safety you may have had with the original array argument.

Only use varargs when you really need a method that accepts a variable number of arguments


 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim McGuire wrote:Cons: unexpected consequences.

One of them is the infamous Arrays.asList problem:
Although the two appear to be identical when taking into account that varargs can also take an array, Arrays.asList takes Objects, not primitives. So instead of a List<Integer>, this call returns a List<int[]> with one element.

Another potential problem is when varargs take Object as its type. Again using Arrays.asList:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!