Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Object... mean? [duplicate]

Tags:

java

arrays

Possible Duplicates:
What does “…” mean in Java?
Java array argument “declaration” syntax

Can anyone confirm if I'm right in seeing the Object... parameter in the method call below:

public static void setValues(PreparedStatement preparedStatement, Object... values)
    throws SQLException
{
    for (int i = 0; i < values.length; i++) {
        preparedStatement.setObject(i + 1, values[i]);
    }
}    

As an array of type Object? I don't recall seeing ... before in Java.

like image 227
Mr Morgan Avatar asked Dec 17 '22 14:12

Mr Morgan


2 Answers

It's equivalent to Object[], but allows the caller to just specify the values one at a time as arguments, and the compiler will create an array. So this call:

setValues(statement, arg1, arg2, arg3);

is equivalent to

setValues(statement, new Object[] { arg1, arg2, arg3 });

See the documentation for the varargs feature (introduced in Java 5) for more information.

like image 144
Jon Skeet Avatar answered Dec 27 '22 18:12

Jon Skeet


From the Java Tutorial (Passing Information to a Method or Constructor):

Arbitrary Number of Arguments

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.

like image 38
Sean Patrick Floyd Avatar answered Dec 27 '22 16:12

Sean Patrick Floyd