Java public void add(int a, int... b) {

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1650221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:40:26  来源:igfitidea点击:

public void add(int a, int... b) {

java

提问by lemotdit

Could someone show me a practical a use of the ... array method delcaration? Is it just a way to declare an optional parameter instead of passing null value?

有人可以向我展示...数组方法声明的实际用法吗?它只是一种声明可选参数而不是传递空值的方法吗?

public void add(int a, int... b) {
 // do something
}

add(1);
add(1,2,3); 

采纳答案by Welbog

It's a shorthand for you when you're writing code that will use a function that can take an array as a parameter.

当您编写将使用可以将数组作为参数的函数的代码时,它是您的简写。

It's generally easier to write add(1,2,3,4);than it is to write add(new int[] {1,2,3,4});, right? It's also clearer when it needs to be read and maintained by future programmers later.

这是通常更容易写add(1,2,3,4);比它是写add(new int[] {1,2,3,4});,对不对?以后需要被未来的程序员阅读和维护时,它也更清晰。

Think about it this way: which function would you call, the one where you have to create an array every time, or the one where you can just pass in as many parameters as you want?

这样想一想:你会调用哪个函数,每次都必须创建一个数组,或者你可以传入任意数量的参数?

回答by Brian Agnew

The Formatterclass is such a practical use:

格式化类是这样的实际应用:

Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%4s %3s %2s %1s", "a", "b", "c", "d")

An arbitrary number of parameters can be passed in to be formatted using the first parameter, which is the format string itself.

可以传入任意数量的参数以使用第一个参数进行格式化,该参数是格式字符串本身。

回答by NickDK

Derived from you example you could make a method to have the sum of all the ints you pass to the method:

从您的示例派生,您可以创建一个方法来获得传递给该方法的所有整数的总和:

    public int sum(int a, int... b) {
    int sum = a;
    for (int i : b) {
        sum += i;
    }
    return sum;
}

回答by mipadi

String.formatis a pretty good practical example. The method doesn't know how many formatters will appear in the format string, so it accepts a variable number of arguments, and there should be a one-to-one mapping of formatters (in the format string) to objects passed into the method.

String.format是一个很好的实际例子。该方法不知道有多少格式化程序会出现在格式字符串中,因此它接受可变数量的参数,并且应该有格式化程序(在格式字符串中)到传递给方法的对象的一对一映射.

It's not so much a way of declaring an option parameter rather than null, as it is to declare a method that can deal with multiple arguments. Basing my example off of mine, you could write a summethod that takes a variable number of arguments and sums them all together:

与其说它是声明一个选项参数而不是 null 的方式,不如说是声明一个可以处理多个参数的方法。以我的示例为基础,您可以编写一个sum方法,该方法采用可变数量的参数并将它们相加:

public int sum(int... ns)
{
    int sum = 0;
    for (int n : ns) {
        sum += n;
    }
    return sum;
}

That way, you could pass in 2, 3, 4, or even 100 numbers to sum, depending on your need at the time.

这样,您可以传入 2、3、4 甚至 100 个数字进行求和,具体取决于您当时的需要。

回答by kungfuice

Before varargs a method that took an arbitrary number of values required you to create an array put the values into the array prior to invoking the method. Example here is how the MessageFormat class to format a message used to look:

在 varargs 之前,采用任意数量值的方法要求您创建一个数组,然后在调用该方法之前将这些值放入数组中。这里的示例是 MessageFormat 类如何格式化用于查看的消息:

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);

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

必须在数组中传递多个参数仍然是正确的,但可变参数功能可以自动化并隐藏该过程。此外,它与预先存在的 API 向上兼容。因此,例如, MessageFormat.format 方法现在具有以下声明:

public static String format(String pattern,
                            Object... arguments);

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position. Given the new varargs declaration for MessageFormat.format, the above invocation may be replaced by the following shorter and sweeter invocation:

最后一个参数类型后的三个句点表示最后一个参数可以作为数组或参数序列传递。Varargs 只能用于最后的参数位置。鉴于 MessageFormat.format 的新 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");

So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

那么什么时候应该使用可变参数呢?作为客户,只要 API 提供它们,您就应该利用它们。核心 API 的重要用途包括反射、消息格式化和新的 printf 工具。作为 API 设计人员,您应该谨慎使用它们,只有在好处确实令人信服时。一般来说,你不应该重载 varargs 方法,否则程序员很难弄清楚调用的是哪个重载。

From: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html

来自:http: //java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html