java 将字符串数组值直接传递给 setter 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14108159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing string array values directly to setter method
提问by Mercenary
There's a String array that I have which has setter and getter methods. How do I directly pass values {"one", "two"}
to the setter method rather than setting the values to a variable first and then passing the parameter?
我有一个 String 数组,它有 setter 和 getter 方法。如何直接将值传递{"one", "two"}
给 setter 方法,而不是先将值设置为变量,然后再传递参数?
String[] arr1 = {};
public String[] getArr1() {
return arr1;
}
public void setArr1(String[] arr1) {
this.arr1 = arr1;
}
..expecting something like setArr1(?);
...
..期待像setArr1(?);
......
回答by Scorpion
You could use setArr1(new String[]{"one", "two"})
你可以用 setArr1(new String[]{"one", "two"})
Alternatively, you could make use of varargs and change your method signature to
setArr1(String... values)
and use the method as setArr1("one", "two")
或者,您可以使用可变参数并将您的方法签名更改为
setArr1(String... values)
并将该方法用作setArr1("one", "two")
回答by Amit Deshpande
回答by Pradeep Simha
setArr1(new String[]{"one","two","three"});
Try like this
像这样尝试
回答by Subhrajyoti Majumder
try this - setArr1(new String[]{"one", "two"})
试试这个 - setArr1(new String[]{"one", "two"})
回答by Manish Nagar
use this code this is setter method
使用此代码这是 setter 方法
public void setSubTaught(int pos, String value)
{
subjectsTaught[pos]=value;
}
this is getter method
这是getter方法
public String getSubTaught()
{
String sub = Arrays.toString(subjectsTaught);
int len = sub.length();
String fix = sub.substring(1,len-1);
return fix;
}
回答by subodh
Your setArr1(String[] arr1)
is taking array of string as a parameter so you can set as normal way we set setter methods.
您 setArr1(String[] arr1)
将字符串数组作为参数,因此您可以按照我们设置 setter 方法的正常方式进行设置。
yourObject.setArr1(new String[]{"string1", "string2"});