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("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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With