Java数组作为参数 [英] Java Arrays as Parameters
问题描述
你能传递一个新的数组作为一种方法,仍然有阵列中的数据?
Can you pass a new array as a method, and still have data in that array?
例如,我有这样的方法:美孚(字符串[])
,我想这样称呼它富(新的String [ ] S = {字符串1,字符串2})
。但是,这不是有效的Java。
For example, I have this method: foo(String[])
, and i want to call it like thisfoo(new String[] s = {"String1", "String2"})
. But that's not valid Java.
推荐答案
这是一个有效的Java方法(如,它编译和你想要做什么):
This is a "valid Java way" (as in, it compiles and does what you want):
foo(new String[] {"String1", "String2"});
如果您需要更改此方法的机会,那么你也可以考虑改变方法采取的可变参数参数:
If you have the opportunity to change this method, then you can also consider to change the method to take a varargs argument:
public void foo(String... strings) {
// ...
}
然后就可以按如下方式使用它,而无需显式地创建一个数组:
Then you can use it as follows without the need to explicitly create an array:
foo("String1", "String2");
以下是那么也是有效的:
The following is then also valid:
foo("String1");
和
foo("String1", "String2", "String3");
,甚至更多。
这篇关于Java数组作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!