M
M
MaxLich2017-04-06 10:37:38
Java
MaxLich, 2017-04-06 10:37:38

How to convert ArrayList to int[]?

It is necessary to form an array of numbers, and its exact size is not known in advance (it depends on the input data, not directly). Therefore I apply ArrayList. Numbers are whole, natural. But at the output, I need to get a regular array of ints (primitive type). So far, I found the toArray method of ArrayList, but I can’t figure out how to use this method to convert an object of type ArrayList into an array of type int[].
You can, of course, use a loop, but it seems to me that this is not the best and simplest solution + time-consuming and memory-consuming (and there are some restrictions on this).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gleendo, 2017-04-06
@MaxLich

public class App {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
        int[] arr = new int[list.size()];

        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }

        System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
    }
}

Or
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
Integer[] arr = list.toArray(new Integer[0]);

D
Dmitry Alexandrov, 2017-04-06
@jamakasi666

If Java 8 then you can do this:
If Java 7-8 then you can use apache commons like this:
Option using google guava:
well, the options that have already been written above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question