What does "public Weatherman (Integer ... zips) {" mean in java

I am trying to read some Java code from a tutorial, I do not understand the line:

 public Weatherman(Integer... zips) {
  • I don’t understand what it represents ... if it was just (Integer zips), I would understand that there is an Integer class variable called zips. But ... I'm embarrassed.
+5
source share
5 answers

This is the syntax sugar "varargs", which allows you to call the constructor in the following ways:

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

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

+13
source

This is "vararg". It can handle any number of arguments Integer, i.e.

new Weatherman(1);

new Weatherman();

new Weatherman(1, 7, 12);

Integer.

+5

varargs feature Java, Java 1.5.

zips - Integer , .

+3

Java-:

, varargs, . varargs, , . ( varargs, ).

varargs, ( ,...), . , .

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, the corners are treated as an array. A method can be called either by an array or by a sequence of arguments. The code in the body of the method will treat the parameter as an array anyway.

+2
source

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

0
source

All Articles