有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java什么是对象。。。意思是

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

有人能确认我在下面的方法调用中看到的Object...参数是否正确吗:

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

作为类型为Object的数组?我不记得以前在Java中见过...


共 (3) 个答案

  1. # 1 楼答案

    您看到的是一个varargs参数。关于它的文件可以在here找到

    Varargs相当于一个对象数组,但是有语法上的糖分使调用该方法更容易。因此,旧方法是(此代码来自上面的文档):

    Object[] arguments = {
        new Integer(7),
        new Date(),
        "a disturbance in the Force"
    };
    
    String result = MessageFormat.format(
        "At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", arguments);
    

    使用varargs,您可以编写:

    String result = MessageFormat.format(
        "At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", 7, new Date(), "a disturbance in the Force");
    

    注意,自动装箱有助于将int 7转换为new Integer(7),而无需显式声明它

  2. # 2 楼答案

    来自Java教程(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.

  3. # 3 楼答案

    它相当于Object[],但允许调用方一次只指定一个值作为参数,编译器将创建一个数组。所以这个电话:

    setValues(statement, arg1, arg2, arg3);
    

    相当于

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

    有关更多信息,请参见documentation for the varargs feature(在Java5中引入)