Initialize array in method argument [duplicate] Initialize array in method argument [duplicate] arrays arrays

Initialize array in method argument [duplicate]


Java has an equivalent construct:

import java.util.Arrays;public class Foo {   public void method(String[] myStrArray) {      System.out.println(Arrays.toString(myStrArray));   }   public static void main(String[] args) {      Foo foo = new Foo();      foo.method(new String[]{"hello", "goodbye"}); // **array created inline**   }}


@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 classclass Array {  public static <A> A[] of(A ... elements) {    return elements;  }}// Main classclass 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"));  }}


Java has varargs methods:

public void foo(String ... args){    for(String arg : args){        // do something    }}

You can call such a method with zero to n parameters, the compiler creates an array from the parameters, e.g. the method is equivalent to this Signature:

public void foo(String[] args)