Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to transform int[] to List<Integer> in Java? [duplicate]

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 } 
like image 538
Roman Avatar asked Jul 08 '11 16:07

Roman


People also ask

How do you add an int array to an ArrayList in Java?

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.

How do you copy an array to an ArrayList?

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.


2 Answers

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.

like image 63
Dan Tao Avatar answered Sep 16 '22 14:09

Dan Tao


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.

like image 41
Op De Cirkel Avatar answered Sep 19 '22 14:09

Op De Cirkel