I'm not entirely comfortable with generics and thus haven't found a solution to this yet. I have these three methods:
public static List<ObjectA> objectAAsList(ObjectA ... items) {
return new ArrayList<>(Arrays.asList(items));
}
public static List<ObjectB> objectBAsList(ObjectB ... items) {
return new ArrayList<>(Arrays.asList(items));
}
public static List<ObjectC> objectCAsList(ObjectC ... items) {
return new ArrayList<>(Arrays.asList(items));
}
How can I create a single method that takes a vararg of T (or something) and creates an ArrayList of it?
Java static code analysis: Arrays should not be created for varargs parameters.
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.
Use List. toArray(T[] arr) : yourVarargMethod(yourList.
Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.
Just replace your type with a type variable:
public static <T> List<T> genericAsList(T ... items) {
return new ArrayList<>(Arrays.asList(items));
}
Note that you could look at how Arrays.asList
is declared, since it does largely the same thing, from a type perspective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With