Java, the most effective way to pass string array as method parameters

Why passing {a, B, C} to a method doesn't work? 7

String[] args = {"a","b","c"};
method(args);


private void method(String[] args){
    return args;
}@H_419_4@ 
 

为什么我无法做到以下没有错误?

method({"a","c"});@H_419_4@ 
 

这段代码只是为了证明这一点,而不是我正在使用的实际方法.我想做第二个方法来清理我的代码,并避免在我只使用它们一次传递给我的方法时声明十几个不同的数组.

问题的核心是什么是最有效的方法来传递字符串数组作为方法参数.

Solution

I suspect you want to use varargs You don't even need to create an array to send variable length parameters

String[] strings = method("a","c");

private String[] method(String... args){
    return args;
}@H_419_4@ 
 

要么

String[] strings = array("a","c");

private <T> T[] array(T... args){
    return args;
}@H_419_4@ 
 

或者如果你想进一步浓缩

String[] strings = array("a,c");

private String[] array(String args){
    return args.split(",?");
}@H_419_4@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>