Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array in method argument [duplicate]

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!

like image 279
aksamit Avatar asked May 21 '11 12:05

aksamit


People also ask

Can we initialize array two times?

No. The array is not being created twice. It is being created once and then it is being populated.

How do you initialize an array in a method?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.


4 Answers

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**
   }
}
like image 162
Hovercraft Full Of Eels Avatar answered Oct 07 '22 15:10

Hovercraft Full Of Eels


@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"));
  }
}
like image 22
missingfaktor Avatar answered Oct 07 '22 16:10

missingfaktor


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)
like image 5
Sean Patrick Floyd Avatar answered Oct 07 '22 14:10

Sean Patrick Floyd


No

But we have anonymous class.

foo(new Runnable(){public void run(){}});
like image 2
jmj Avatar answered Oct 07 '22 15:10

jmj