Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 420
Alex Turbin Avatar asked Nov 29 '10 09:11

Alex Turbin


1 Answers

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

like image 50
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet