开发者

Arrays.asList(T[] array)?

开发者 https://www.devze.com 2023-02-21 23:29 出处:网络
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 ma

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);
   ret开发者_开发百科urn result;
}


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


As you probably already know, there is a Static class called java.util.Collections which has a number of useful methods for dealing wit arrays such as searching and sorting.

As for your question, the Collection interface specifies methods to add, remove and toArray, amongst others. For one reason or another, the API's authors decided that the add and addAll method will be the only input functions provided to the user.

One explanation for why Java Lists cannot add arrays of objects is that Lists use an iterator and iterators are more strict in their scrolling (i.e. going to the next value) than Arrays which do not have to have all their index values i=(1, 2, 5, 9, 22, ...).

Also, Arrays are not type safe; that is, they cannot guarantee that all their elements conform to a specific super-class or interface, whereas generics (of which List is a member) can guarantee type safety. Hence, the list has the chance to validate each item using the add method.

I think that you can rest assure that your method of adding an array to a list is one of the most (if not most) efficient way of achieving this effect in Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消