ProgramPower
ProgramPower

Reputation: 338

Standard Java varargs converter to array

My question is quite simple.

Is there a method in core Java that does the following code:

<T> T[] asArray(T... values) {
    return values;
}

I tried looking for it in Arrays class, but there seems to be no such method.

To give you a context:

The previous person who worked on this code decided that varargs is better than regular array in class constructor (even though it IS supposed to be an array). Right now I have to add another generic array as the last parameter of the constructor thus transforming this code:

public Clazz(String... values) {
}

to this

public <T> Clazz(String[] values, T[] additionalParameters)

As a result I need to refactor all places where this constructor was used. What is worse that there is a couple other classes that follow the same pattern and I need to be modify them sometime in the future. And that is where above mentioned method asArray could help.

I know that it is better to just replace varargs with explicit array creation in every occurrence (and that is what I am going to do anyway), but I still want to know if there is such method already (just out of mere curiosity).

Upvotes: 4

Views: 5779

Answers (2)

dimo414
dimo414

Reputation: 48824

The JDK doesn't need to provide such a method since you get the same behavior by simply constructing an array - e.g.:

// these two statements are conceptually identical
String[] a = asArray("a", "b", "c");
String[] b = new String[]{"a", "b", "c"};

Upvotes: 10

Jean Logeart
Jean Logeart

Reputation: 53829

You can do:

T[] a = Stream.of(t1, t2, t3).toArray();

Upvotes: -2

Related Questions