你什么时候在 Java 中使用可变参数? [英] When do you use varargs in Java?

查看:30
本文介绍了你什么时候在 Java 中使用可变参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我害怕可变参数.我不知道它们有什么用.

I'm afraid of varargs. I don't know what to use them for.

另外,让人们随心所欲地传递尽可能多的参数感觉很危险.

Plus, it feels dangerous to let people pass as many arguments as they want.

什么是适合使用它们的上下文的示例?

What's an example of a context that would be a good place to use them?

推荐答案

Varargs 对于需要处理不确定数量对象的任何方法很有用.一个很好的例子是 String.format.格式字符串可以接受任意数量的参数,因此您需要一种机制来传入任意数量的对象.

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String.format. The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

String.format("This is an integer: %d", myInt);
String.format("This is an integer: %d and a string: %s", myInt, myString);

这篇关于你什么时候在 Java 中使用可变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆