Java“params”在方法签名? [英] Java "params" in method signature?

查看:185
本文介绍了Java“params”在方法签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,如果希望方法具有不确定数量的参数,可以在方法签名中将最终参数设为 params ,以便方法参数看起来如此像一个数组,但允许每个使用该方法的人传递与调用者想要的那种类型的参数。

In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.

我很确定Java支持类似的行为,但我不能找出如何做到这一点。

I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.

推荐答案

在Java中,它被称为 varargs ,语法看起来像一个常规参数,但后面带有省略号(...)类型:

In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:

public void foo(Object... bar) {
    for (Object baz : bar) {
        System.out.println(baz.toString());
    }
}

vararg参数必须始终是方法签名中的 last 参数,并且就像您收到该类型的数组一样进行访问(例如 Object [] 在这种情况下)。

The vararg parameter must always be the last parameter in the method signature, and is accessed as if you received an array of that type (e.g. Object[] in this case).

这篇关于Java“params”在方法签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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