Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

java premitive int array to ArrayList<Integer>

  1. User

    java premitive int array to ArrayList

  2. 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, intArray is the primitive int array that you want to convert to an ArrayList of Integer objects. The intList is 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, intList will contain all the Integer objects converted from the primitive int array.