7

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?

DoeMoeJoe
  • 107
  • 6

2 Answers2

10

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

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);
     ...
}
debus
  • 630
  • 4
  • 9
  • Thanks, but I don't want to have to state the class of the objects I'm passing in when I use it. – DoeMoeJoe Aug 19 '16 at 09:02
  • 1
    I don't see any advantage of this approach - how is this "better"? – Hulk Aug 19 '16 at 09:54
  • @Hulk, [Take a look at](http://stackoverflow.com/questions/1530353/in-what-situations-is-static-method-a-good-practice). (It's true that you can consider VarArgsToList as utility, but i still prefer the Function approach. Just my opinion) – debus Aug 19 '16 at 10:08
  • The only advantage of this would be the ability to mock this behavior when testing, but this would only be relevant if you are able to somehow inject the `VarArgsToList` from the outside. If the instance is explictly created at the call-site, this adds nothing but verbosity. – Hulk Aug 19 '16 at 10:23