2

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?

Cataclysm
  • 7,592
  • 21
  • 74
  • 123

4 Answers4

4

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

show(new String[] {"a","b","c"})
dpr
  • 10,591
  • 3
  • 41
  • 71
3

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!

anacron
  • 6,443
  • 2
  • 26
  • 31
2

What you are looking for is not a way to pass an array to a method without declare it, you are looking for a "single line data instatiation for array"... or by the real name "in-line declare"

show(new Object[]{"a","b","c"});
Rafael Lima
  • 3,079
  • 3
  • 41
  • 105
0

You can accomplish this by using varargs. A simple edit to your function will not only allow an array of objects but allow you to accomplish what you are looking for.

Instead of using Object[] use Object...

Cameron
  • 58
  • 7