Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - A method that takes vararg and returns arraylist?

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?

like image 776
DoeMoeJoe Avatar asked Aug 19 '16 08:08

DoeMoeJoe


People also ask

Can I pass array to Varargs Java?

Java static code analysis: Arrays should not be created for varargs parameters.

What is Vararg in Java?

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.

How do you pass a list to a variable argument in Java?

Use List. toArray(T[] arr) : yourVarargMethod(yourList.

Should I use varargs in java?

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.


1 Answers

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.

like image 52
Andy Turner Avatar answered Nov 14 '22 23:11

Andy Turner