问题
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?
回答1:
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.)
回答2:
You can use Google Guava Library (AKA Google Collections) for this:
String[] ary = {"a", "b"};
List<String> l = Lists.newArrayList(ary);
http://code.google.com/p/guava-libraries/
回答3:
It seems that the reason that ArrayList does not implement any constructor itself but just delegates the call to super class constructor, i.e. constructor of AbstractList. There are a lot of list implementations including LinkedList that should not have constructor that accepts array.
I think that absence of constructor that accepts array and presence of static utility method in class Arrays is an example of good design and better code reuse. That's right that it cause us to write a little bit more verbose code, but this is the price.
BTW if you are using static import java.util.Arrays you can then call asList() without mentioning Arrays, so the code is not to verbose.
回答4:
java.util.Arrays internally uses its own version of ArrayList class...
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable
{
...
}
No idea why it is not included as a standard constructor call... but you can follow the lead of java.util.Arrays and have your own version of Arraylist.
来源:https://stackoverflow.com/questions/4302248/why-there-is-no-arraylistt-t-constructor