2010.04.08 09:45

Java Variable Arguments (Varargs)

The varargs, or variable arguments, feature allows a developer to declare that a method can take a variable number of parameters for a given argument. The vararg must be the last argument in the formal argument list.

You might use varargs to allow adding one to many objects to a collection that you have defined by using a single add method call. Suppose you need a method that writes any number of records to the console. Using varargs, you can make any of the following method calls:

write("line 1");
write("line 2", "line 3");
write("line 4", "line 5", "line 6", "line 7", "line 8", "line 9", "line 10");

Before 1.5, you would need to define overloaded versions of the write method to accomplish this. This isn't an effective solution if you want to be able to support any number of records being passed in.

The write method introduces a couple new bits of syntax:

public void write(String... records) {
    for (String record: records)

First, the records argument is defined as type String.... This indicates to the compiler that calling code can pass a variable number of String parameters. For all other intents and purposes, however, String... equates to a String array (String[]).

The Enhanced For Loop
Second, the code uses the new enhanced for loop syntax that is being introduced in Java 1.5. You read the for loop in the example above as "for each String record in records." Or more explicitly, "for each object stored in the String array records, assign the object to a reference named record of type String."

The enhanced for loop, also known as foreach, is a nice feature that can also be used with any of the collection classes in Java 1.5. In addition, Java supplies hooks that allow you to make your own class iterable, so that it can be referenced in a foreach loop.

Behind the Scenes
There isn't any real magic going on with respect to varargs. Behind the scenes, Java is converting the new syntax into equivalent code that would work under Java 1.4 and older versions. The example above is equivalent to coding the following:

write(new String[] { "line 1" });
write(new String[] { "line 2", "line 3" });
write(new String[] { "line 4", "line 5", "line 6"});
// ... 
public void write(String[] records) {
    for (String record: records)

[출처] Looking at Varargs in J2SE 1.5

Trackback 0 Comment 0