-1

I find myself re-implementing List creation method. But I'm sure that it is already implemented in some widely used library (if not in java itself). So my question is: Which useful library to include, to get functionality of following code:

public static <T> List<T> buildList(T... args) {
    ArrayList<T> list = new ArrayList<T>();
    for (T arg : args)
    {
        list.add(arg);
    }
    return list;
}

EDIT: Already found what i was looking for: http://code.google.com/p/google-collections/ I just import statically:

import static com.google.common.collect.Lists.newArrayList;

and use:

methodThatTakesArray(newArrayList("fst", "snd", "lst"));
Lauri
  • 1,859
  • 2
  • 14
  • 17

2 Answers2

2

java.util.Arrays#asList is what you are looking for.

bezmax
  • 25,562
  • 10
  • 53
  • 84
  • I did consider that, but its not as convenient :( – Lauri Feb 29 '12 at 10:48
  • @Lauri Why isn't it? It does the same thing you asked. If you need a dynamic-sized list, you can: `list = new ArrayList(Arrays.asList(myArray))` – bezmax Feb 29 '12 at 11:01
  • I don't want to create array. Sure it's not _that_hard_ but it's unnecessary. Sure my method could work on array, but it also works on varargs AND that is what I'm after. Anyway, i found solution, check my original posts' edit. – Lauri Feb 29 '12 at 12:04
0

A short hand to convert arrays to arraylist.

ArrayList<T> arraylist = new ArrayList<T>(Arrays.asList(array))

Check this out, Create ArrayList from array

Community
  • 1
  • 1
John Eipe
  • 10,922
  • 24
  • 72
  • 114