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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)