问题
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?
回答1:
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.
回答2:
I think a Function is a better approach than a static method. You can define a Function :
public class VarArgsToList<T> implements Function<T[], List<T>> {
@Override
public List<T> apply(final T... items) {
return new ArrayList<>(Arrays.asList(items));
}
}
and apply it wherever:
public static void main(final String... arg) {
...
final List<String> list1 = new VarArgsToList<String>().apply(arg);
...
final List<MyObject> list2 = new VarArgsToList<MyObject>().apply(myObject1, myObject2, myObject3);
...
}
来源:https://stackoverflow.com/questions/39034234/java-a-method-that-takes-vararg-and-returns-arraylist