Is there a better way of achieving this?
public static List toList(String[] array) {
List list = new ArrayList(array.length);
What do you mean by better way:
more readable:
List<String> list = new ArrayList<String>(Arrays.asList(array));
less memory consumption, and maybe faster (but definitely not thread safe):
public static List<String> toList(String[] array) {
if (array==null) {
return new ArrayList(0);
} else {
int size = array.length;
List<String> list = new ArrayList(size);
for(int i = 0; i < size; i++) {
list.add(array[i]);
}
return list;
}
}
Btw: here is a bug in your first example:
array.length
will raise a null pointer exception if array is null, so the check if (array!=null)
must be done first.
Yes, there is. You can use the Arrays class from the java.util.* package. Then it's actually just one line of code.
List<String> list = Arrays.asList(array);
What about :
List myList = new ArrayList();
String[] myStringArray = new String[] {"Java", "is", "Cool"};
Collections.addAll(myList, myStringArray);
You can try something like this:
List<String> list = new ArrayList<String>(Arrays.asList(array));
public ArrayList(Collection c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.
Taken from here
Have you checked Arrays.asList()
; see API
You can use:
list.addAll(Arrays.asList(array));