简体   繁体   English

java:我如何创建一个支持任意数量参数的函数?

[英]java: how can i create a function that supports any number of parameters?

is it possible to create a function in java that supports any number of parameters and then to be able to iterate through each of the parameter provided to the function ? 是否可以在java中创建一个支持任意数量参数的函数,然后能够遍历提供给函数的每个参数?

thanks 谢谢

kfir 幼狮

Java has had varargs since Java 1.5 (released September 2004). 自Java 1.5(2004年9月发布)以来,Java已经有了varargs

A simple example looks like this... 一个简单的例子看起来像这样......

public void func(String ... strings) {
    for (String s : strings)
         System.out.println(s);
}

Note that if you wanted to require that some minimal number of arguments has to be passed to a function, while still allowing for variable arguments, you should do something like this. 注意,如果你想要一些最小数量的参数必须传递给一个函数,同时仍然允许变量参数,你应该做这样的事情。 For example, if you had a function that needed at least one string, and then a variable length argument list: 例如,如果您有一个至少需要一个字符串的函数,然后是一个可变长度参数列表:

public void func2(String s1, String ... strings) {

}

As other have pointed out you can use Varargs: 正如其他人指出你可以使用Varargs:

void myMethod(Object... args) 

This is actually equivalent to: 这实际上相当于:

void myMethod(Object[] args) 

In fact the compiler converts the first form to the second - there is no difference in byte code. 事实上,编译器将第一种形式转换为第二种形式 - 字节代码没有区别。 All arguments must be of the same type, so if you want to use arguments with different types you need to use an Object type and do the necessary casting. 所有参数必须是相同的类型,因此如果要使用具有不同类型的参数,则需要使用Object类型并执行必要的转换。

是的,使用varargs

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

相关问题 如何在Java中创建一个包含可变数量参数的“除法”函数 - how to create a "Division" function which contains variable number of parameters in Java 如何仅使用Java SE创建支持多个客户端请求的Java Web服务? - How can i create a java web service that supports multiple client requests using only java SE? 如何创建一个 Java 算法,该算法可以接受任意数量的玩家并将它们唯一地配对任意次数? - How can I create a Java algorithm that takes any number of players and pair them up any number of times uniquely? 如何使用Java创建“新”终端参数? - How can I create “new” terminal parameters using Java? 如何判断安装的 Java 是否支持模块? - How can I determine whether the installed Java supports modules or not? 如何测试 Java 集合是否支持添加操作? - How can I test whether a Java collection supports the add operation? 关于如何在Java按钮中创建电子邮件链接的任何建议 - Any suggestions on how i can create an email link in a java button 如何创建接受可变数量参数的 Java 方法? - How can I create a Java method that accepts a variable number of arguments? 如何制作接受任何类型变量的 Java 函数? - How can I make a Java function that accepts any type of variable? 如何创建一个返回数字总和的乘积的函数 - How can I create a function that returns Product of Digit Of Sum of a number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM