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

杀马特。学长 韩版系。学妹 提交于 2019-11-27 15:26:36

Java has had varargs since Java 1.5 (released September 2004).

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:

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.

Yes, using varargs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!