I have a method as
private void show(Object[] arr) {
for (Object o : arr) {
System.out.println(o);
}
}
I would like to call this method as
// belows are not valid but I'd like to achieve
show({1,2,3});
show(new String["a","b","c"])
but I don't want to create an array to call this method. (Please don't be suggest to change the signature of my show method.This is just an example.Actual method that I use is from 3rd party lib.)
How can I achieve this by utility classes or anything else?
You can either use varargs as mentioned in the comments or declare the array this way:
show(new String[] {"a","b","c"})
Create a varargs wrapper method:
private void myShow(Object... arr){
show(arr);
}
// No change to your existing 3rd party method:
private void show(Object[] arr) {
for (Object o : arr) {
System.out.println(o);
}
}
You can then call the wrapper method like this:
myShow("a","b","c");
myShow(1,2,3,4);
Hope this helps!
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