简体   繁体   中英

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?

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.

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);
     ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM