views:

136

answers:

5

I am trying to read some Java code from a tutorial, I don't understand the line:

 public Weatherman(Integer... zips) {
  • I don't understand what the ... represents if it was just (Integer zips) I would understand that there is a variable of class Integer called zips. But the ... are confusing me.
+13  A: 

Those are "varargs," syntactic sugar that allows you to invoke the constructor in the following ways:

new Weatherman()
new Weatherman(98115);
new Weatherman(98115, 98072);
new Weatherman(new Integer[0]);

Under the covers the arguments are passed to the constructor as an array, but you do not need to construct an array to invoke it.

Steve Reed
A: 

If I remember good it is used when there is a variable number of parameters

Clement Herreman
+5  A: 

That’s a “vararg”. It can handle any number of Integer arguments, i.e.

new Weatherman(1);

is just as valid as

new Weatherman();

or

new Weatherman(1, 7, 12);

Within the method you access the parameters as an Integer array.

Bombe
+2  A: 

From the Java tutorials:

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).

To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x) 
  + (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
    lengthOfSide1 = Math.sqrt(squareOfSide1);
    // more method body code follows that creates 
    // and returns a polygon connecting the Points
}

You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.

MicSim
+3  A: 

You are seeing the varargs feature of Java, available since Java 1.5.

zips is an array of Integer inside the constructor, but the constructor can be called with a variable number of arguments.

starblue