Alex Rivera | Logout

Initialize array in method argument

Asked 2011-05-21T12:19:45.557
39

In PHP you can do the following:

method(array("a", "b"));

Can you in Java initialize a String array as an argument in the method call, something like tihs:

method(new String[] = {"a", "b"});

Thanks!

Edit
Report

1 Answer

13

@Hovercraft's answer shows how to create an array inline in Java.

You could further improve on that solution by using an utility method (one that makes use of Java's limited type inference) to get rid of the redundant array type annotation.

Code:

import java.util.Arrays;

// Utility class
class Array {
  public static <A> A[] of(A ... elements) {
    return elements;
  }
}

// Main class
class Main {
  public static void method(String[] s) {
    System.out.println(Arrays.toString(s));
  }

  public static void main(String[] args) {
    method(Array.of("a", "b", "c"));
  }
}
answered 2011-05-21T18:38:51.833

Your Answer