Java Variable Length Parameter vs. Array, Simply Syntactic Sugar? -


i taking data structures , algorithms course fun @ local community college. course's textbook y. daniel liang's introduction java programming, 10th edition. book, itself, pretty solid.

in dealing java.util.arrays, liang mentions java's "variable-length" parameter. writes (p. 265):

java treats variable-length parameter array. can pass array or variable number of arguments variable-length parameter. when invoking method variable number of arguments, java creates array , passes arguments it.

an example being:

public static void (int... toes) {     //... code } 

however, liang never explains origin or advantage of variable-length parameter. if, liang says, variable-length parameter "converted" array, advantage? there software design pattern or engineering goal facilitated variable length parameter?

in other words, above code snippet offer not offered below:

public static void (int[] toes) { // ... 

in java, varargs syntactical sugar creating array when calling method. example, these 2 calls equivalent:

void foo(string... args) { ... }  foo("hello", null, "world", xyz);  // java 1.5+ foo(new string[]{"hello", null, "world", xyz});  // versions of java 

varargs doesn't make new possible (by definition of syntactic sugar), reduces verboseness , makes constructs more agreeable implement. example, of favorite uses of vararg include: printstream.printf(), string.format(), method.invoke().

other applications of varargs:

// 1 in java standard library collections: void addall(collection<? super t> c, t... elements);  // custom examples int max(int... nums); void dooperation(file x, string y, someenum options...); 

additionally, java's varargs bring language parity vararg support in c, python, javascript, , other languages. if recurring design (such max()) works best varargs, java no longer odd language requires uglier implementation.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -