Alex Rivera | Logout

Why there is no ArrayList(T[] t) constructor?

Asked 2010-11-29T09:12:45.093
17

It is very common to initialize list by array of objects in such way:

Foo[] objs = ...;
ArrayList<Foo> list = new ArrayList<Foo>(Arrays.asList(objs));

I wonder, is there any reason why desiners of ArrayList didn't include constructor with array as parameter, so that it could be initialized like that:

ArrayList<Foo> list = new ArrayList<Foo>(objs);

May be it violates some principles, thread-safety or something else?

Edit
Report

1 Answer

11

I don't know why it's not in the standard library, but Guava's Lists class has newArrayList which even helps with type inference:

ArrayList<Foo> list = Lists.newArrayList(objs);

(You may want to import Lists.newArrayList statically if you use it a lot.)

answered 2010-11-29T09:18:13.127

Your Answer