Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array parameter with inline declare?

Tags:

java

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?

like image 799
Cataclysm Avatar asked Sep 01 '26 11:09

Cataclysm


2 Answers

You can either use varargs as mentioned in the comments or declare the array this way:

show(new String[] {"a","b","c"})
like image 110
dpr Avatar answered Sep 04 '26 00:09

dpr


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!

like image 36
anacron Avatar answered Sep 04 '26 00:09

anacron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!