How can I make passing a list with just one value to an other method less verbose
If I have a method like this
private void setStringList(List<String> aList) { ... }
Then this is obviously possible
private void testOnly() {
List<String> myDummyList = new ArrayList<String>();
myDummyList.add("开发者_JAVA百科someValue");
setStringList(myDummyList);
}
but is there a way to make it less verbose like this
private void testOnly2() {
setStringList(new ArrayList<String>().add("someValue"));
}
I know above is compilation error but just showing to demonstrate what I want to achieve just to make it less verbose.
Yes:
private void testOnly2() {
setStringList(new ArrayList<String>(Arrays.asList("someValue")));
}
or, depending on what you use the argument for in setStringList
:
private void testOnly2() {
setStringList(Arrays.asList("someValue"));
}
Another option is to use an instance-initializer, like this:
private void testOnly2() {
setStringList(new ArrayList<String>() {{
add("someValue");
}});
}
(this creates an anonymous subclass of ArrayList though.)
As well as the suggestions from aioobe which just use the JDK, Guava offers various options, including:
setStringList(Lists.newArrayList("someValue"));
setStringList(ImmutableList.of("someValue"));
You can use:
private void testOnly2() {
setStringList(Collections.singletonList("someValue"));
}
精彩评论