Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.asList(T[] array)?

So there's Arrays.asList(T... a) but this works on varargs.

What if I already have the array in a T[] a? Is there a convenience method to create a List<T> out of this, or do I have to do it manually as:

static public <T> List<T> arrayAsList(T[] a)
{
   List<T> result = new ArrayList<T>(a.length);
   for (T t : a)
     result.add(t);
   return result;
}
like image 575
Jason S Avatar asked Apr 01 '11 14:04

Jason S


1 Answers

Just because it works with varargs doesn't mean you can't call it normally:

String[] x = { "a", "b", "c" };
List<String> list = Arrays.asList(x);

The only tricky bit is if T is Object, where you should use a cast to tell the compiler whether it should wrap the argument in an array or not:

Object[] x = ...;
List<Object> list = Arrays.asList((Object[]) x);

or

Object[] x = ...;
List<Object[]> list = Arrays.asList((Object) x);
like image 149
Jon Skeet Avatar answered Oct 08 '22 04:10

Jon Skeet