Best way to convert int [] to List <Integer> in Java?
Possible duplicate:
How to create an ArrayList (ArrayList <T>) from an array (T []) in Java
How to implement this method:
List<Integer> toList(int[] integers) { ??? //return Arrays.asList(integers); doesn't work } There is probably a built-in method to do this somewhere * (as you noticed, Arrays.asList will not work since it expects Integer[] , not int[] ).
I don't know the Java libraries very well to tell you where it is. But writing your own is pretty 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 drawback of this is that you cannot do this altogether. You will need to write a separate createList method for each type of privileged autobox you want.
* And if not, I really wonder why not.
List<Integer> asList(final int[] integers) { return new AbstractList<Integer>() { public Integer get(int index) { return integers[index]; } public int size() { return integers.length; } }; } List<Integer> toList(int[] integers) { // Initialize result size to length of the incoming array // this way it will not require reallocations ArrayList<Integer> result = new ArrayList<Integer>( integers.length ); for ( int cur: integers ) { result.add( Integer.valueOf( cur ) ); } return result; } 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 a list supported by the new array.
int[] a = {1, 2, 3}; List<Integer> aI = Arrays.asList(ArrayUtils.toObject(a)); EDIT:. This does not work if you want to add() new elements (resize), although the list interface, if you want to be able to add new elements, you can use new ArrayList() , but this will create another copy.
I do not think there is a quick way to do this, unfortunately. I believe that you will have to iterate over the array and add it one at a time.
import java.util.Arrays; import java.util.ArrayList; import java.util.List; public class Listing { public static void main(String[] args) { int[] integers = {1,2,3,4}; java.util.List<Integer> list = new ArrayList<Integer>(); for (int i=0; i< integers.length; i++) { list.add(integers[i]); } System.out.println(list); } } Tested and works as expected!