Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to Collection: Optimized code

Is there a better way of achieving this?

public static List<String> toList(String[] array) {      List<String> list = new ArrayList(array.length);      for(int i=0; i<array.length; i++)         list.add(array[i]);      return list; } 

NOTE: Arrays.asList(a) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.). I don't want that behavior. I assume that MY function above bypasses that (or am I wrong?)

So, here we have the alternative method:

public static List<String> toList(String[] array) {      List<String> list = new ArrayList(array.length);      list.addAll(Arrays.asList(array));      return list; } 

Just looking at it, I don't believe it's FASTER than the first method.

like image 302
marcolopes Avatar asked Nov 23 '10 10:11

marcolopes


People also ask

How do you copy an array to a collection?

Step 1: Declare and initialize the array “countryArray”. Step 2: Declare the list object “countryList”. Step 3 : Now, use the method Collections. addAll(Collections,Array).

Which is faster array or collection?

Arrays due to fast execution consumes more memory and has better performance. Collections, on the other hand, consume less memory but also have low performance as compared to Arrays. Arrays can hold the only the same type of data in its collection i.e only homogeneous data types elements are allowed in case of arrays.

Why arrays are faster than collections?

An Array is a collection of similar items. Whereas ArrayList can hold item of different types. An array is faster and that is because ArrayList uses a fixed amount of array.


2 Answers

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.

like image 171
Ralph Avatar answered Oct 16 '22 15:10

Ralph


Arrays.asList(array);     

Example:

 List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); 

See Arrays.asList class documentation.

like image 37
jmj Avatar answered Oct 16 '22 15:10

jmj