java premitive int array to ArrayList<Integer>
- User
java premitive int array to ArrayList
- Assistant
To convert a primitive int array to an ArrayList, you can use the following code:
int[] intArray = {1, 2, 3, 4, 5}; ArrayList<Integer> intList = new ArrayList<Integer>(intArray.length); for (int i : intArray) { intList.add(i); }Here,
intArrayis the primitive int array that you want to convert to an ArrayList of Integer objects. TheintListis the ArrayList that will hold the converted Integer objects.To perform the conversion, we first create an empty ArrayList with an initial capacity that is equal to the length of the int array. This is done using the
ArrayList<Integer>(intArray.length)constructor.Next, we use a for-each loop to iterate over each element of the int array. We convert each int element to an Integer object and add it to the ArrayList using the
add()method.At the end of the loop,
intListwill contain all the Integer objects converted from the primitive int array.