简体   繁体   English

如何创建接受可变数量参数的 Java 方法?

[英]How can I create a Java method that accepts a variable number of arguments?

For example, Java's own String.format() supports a variable number of arguments.例如,Java 自己的String.format()支持可变数量的参数。

String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!

How can I make my own function that accepts a variable number of arguments?如何制作自己的接受可变数量参数的函数?


Follow-up question:后续问题:

I'm really trying to make a convenience shortcut for this:我真的想为此创建一个方便的快捷方式:

System.out.println( String.format("...", a, b, c) );

So that I can call it as something less verbose like this:这样我就可以将其称为不那么冗长的东西:

print("...", a, b, c);

How can I achieve this?我怎样才能做到这一点?

You could write a convenience method:你可以写一个方便的方法:

public PrintStream print(String format, Object... arguments) {
    return System.out.format(format, arguments);
}

But as you can see, you've simply just renamed format (or printf ).但正如您所看到的,您只是简单地重命名了format (或printf )。

Here's how you could use it:以下是您可以如何使用它:

private void printScores(Player... players) {
    for (int i = 0; i < players.length; ++i) {
        Player player = players[i];
        String name   = player.getName();
        int    score  = player.getScore();
        // Print name and score followed by a newline
        System.out.format("%s: %d%n", name, score);
    }
}

// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);

// Output
Abe: 11

Bob: 22
Cal: 33
Dan: 44

Abe: 11
Bob: 22
Cal: 33
Dan: 44

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format , so you might as well use format directly.请注意,还有类似的System.out.printf方法,其行为方式相同,但如果您查看实现, printf只是调用format ,因此您不妨直接使用format

This is known as varargs see the link here for more details这被称为可变参数,请参阅此处的链接以获取更多详细信息

In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method.在过去的 Java 版本中,采用任意数量值的方法要求您在调用该方法之前创建一个数组并将这些值放入该数组中。 For example, here is how one used the MessageFormat class to format a message:例如,以下是如何使用 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.必须在数组中传递多个参数仍然是正确的,但 varargs 功能会自动执行并隐藏该过程。 Furthermore, it is upward compatible with preexisting APIs.此外,它与预先存在的 API 向上兼容。 So, for example, the MessageFormat.format method now has this declaration:因此,例如, MessageFormat.format 方法现在具有以下声明:

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

Take a look at the Java guide on varargs .查看有关varargs的 Java 指南。

You can create a method as shown below.您可以创建如下所示的方法。 Simply call System.out.printf instead of System.out.println(String.format(... .只需调用System.out.printf而不是System.out.println(String.format(... .

public static void print(String format, Object... args) {
    System.out.printf(format, args);
}

Alternatively, you can just use a static import if you want to type as little as possible.或者,如果您想尽可能少地输入,您可以只使用静态导入 Then you don't have to create your own method:然后您不必创建自己的方法:

import static java.lang.System.out;

out.printf("Numer of apples: %d", 10);

This is just an extension to above provided answers.这只是上述提供的答案的扩展。

  1. There can be only one variable argument in the method.方法中只能有一个可变参数。
  2. Variable argument (varargs) must be the last argument.变量参数 (varargs) 必须是最后一个参数。

Clearly explained here and rules to follow to use Variable Argument .这里清楚地解释使用Variable Argument 时要遵循的规则。

The following will create a variable length set of arguments of the type of string:以下将创建字符串类型的可变长度参数集:

print(String arg1, String... arg2)

You can then refer to arg2 as an array of Strings.然后,您可以将arg2称为字符串数组。 This is a new feature in Java 5.这是 Java 5 中的一个新特性。

The variable arguments must be the last of the parameters specified in your function declaration.变量参数必须是函数声明中指定的最后一个参数。 If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.如果您尝试在可变参数之后指定另一个参数,编译器会抱怨,因为无法确定有多少参数实际上属于可变参数。

void print(final String format, final String... arguments) {
    System.out.format( format, arguments );
}

You can pass all similar type values in the function while calling it.您可以在调用函数时在函数中传递所有相似类型的值。 In the function definition put a array so that all the passed values can be collected in that array .在函数定义中放置一个数组,以便可以在该数组中收集所有传递的值。 eg .例如。

static void demo (String ... stringArray) {
  your code goes here where read the array stringArray
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java 8中,如何创建一个接受布尔条件和带有参数作为参数的lambda的方法? - How to create a method that accepts a boolean criteria and a lambda with arguments as a parameter in Java 8? 方法的 Java 变量号或参数 - Java variable number or arguments for a method 创建一个方法,接受可变长度的Function参数,可能有不同的类型 - Create a method that accepts variable length of Function arguments with possibly different types 如何创建一个接受Java中任何类型的任意数量的参数的方法? - How to make a method which accepts any number of arguments of any type in Java? 如何制作接受任何类型变量的 Java 函数? - How can I make a Java function that accepts any type of variable? "我可以将数组作为参数传递给 Java 中具有可变参数的方法吗?" - Can I pass an array as arguments to a method with variable arguments in Java? 如何创建一个在Java中接受回调函数的方法? - How to create a method that accepts a callback function in java? 如何有条件地将Java中的参数传递给一个采用可变数量参数的方法? - How to conditionally pass parameters in Java to a method that takes a variable number of arguments? 在Android编程中:如何调用接受View类型参数的方法? - In Android programming: How can I call a method that accepts arguments of type View? 如何创建一个自定义ArgumentMatcher来接受其他匹配器的参数? - How can I create a custom ArgumentMatcher that accepts arguments from other matchers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM