Possible Duplicate:
How to create ArrayList (ArrayList<T>) from array (T[]) in Java
How to implement this method:
List<Integer> toList(int[] integers) { ??? //return Arrays.asList(integers); doesn't work }
An array can be converted to an ArrayList using the following methods: Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.
We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.
There's probably a built-in method to do it somewhere* (as you note, Arrays.asList
won't work as it expects an Integer[]
rather than an int[]
).
I don't know the Java libraries well enough to tell you where that is. But writing your own is quite simple:
public static List<Integer> createList(int[] array) { List<Integer> list = new ArrayList<Integer>(array.length); for (int i = 0; i < array.length; ++i) { list.add(array[i]); } return list; }
Obviously one downside of this is that you can't do it generically. You'll have to write a separate createList
method for each autoboxed primitive type you want.
*And if there isn't, I really wonder why not.
Use commons-lang3 org.apache.commons.lang3.ArrayUtils.toObject(<yout int array>)
and then java.util.Arrays.asList(<>)
ArrayUtils.toObject()
will copy the array, and Array.asList()
will simply create list that is backed by new array.
int[] a = {1, 2, 3}; List<Integer> aI = Arrays.asList(ArrayUtils.toObject(a));
EDIT: This wont work if you want to add()
new elements (resize) though the list interface, if you want to be able to add new elements, you can use new ArrayList()
, but this will create one more copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With