Home >Java >javaTutorial >Can Java Methods with Variable Arguments Accept an Array as Multiple Arguments?

Can Java Methods with Variable Arguments Accept an Array as Multiple Arguments?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 21:52:10708browse

Can Java Methods with Variable Arguments Accept an Array as Multiple Arguments?

Can Arguments Be Passed as an Array to a Method with Variable Arguments in Java?

Consider the following desired function:

class A {
  private String extraVar;
  public String myFormat(String format, Object ... args) {
    return String.format(format, extraVar, args);
  }
}

In this scenario, args is interpreted as Object[] within the myFormat method, resulting in a single argument being provided to String.format. However, the aim is to have each Object in args passed as a distinct argument.

Is It Possible?

Yes, it is possible since T... is merely syntactic sugar for T[].

Java Language Specification (JLS) 8.4.1 defines:

The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[].

Example Illustrating Variable Arity Parameter:

public static String ezFormat(Object... args) {
    String format = new String(new char[args.length])
        .replace("<pre class="brush:php;toolbar:false">static void count(Object... objs) {
    System.out.println(objs.length);
}

count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws NullPointerException!!!
", "[ %s ]"); return String.format(format, args); } public static void main(String... args) { System.out.println(ezFormat("A", "B", "C")); // prints "[ A ][ B ][ C ]" }

In the main method, args is a String[], which is passed to ezFormat. The method treats it as Object[] because of covariance.

Varargs Gotchas:

Passing null

    int[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ [I@13c5982 ]"

To work around this, call with Object[] { null } or (Object) null.

Adding Extra Arguments to an Array

To pass an array of primitive types, wrap it in a reference array:

    Integer[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ 1 ][ 2 ][ 3 ]"

The above is the detailed content of Can Java Methods with Variable Arguments Accept an Array as Multiple Arguments?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn