Java - A method that takes vararg and returns arraylist?

本秂侑毒 提交于 2021-01-27 04:18:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!