views:

3872

answers:

10

How do I convert int[] into List<Integer> in Java?

Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.

A: 

Use Arrays.asList()

To deal with autoboxing issues, you obviously need to convert the int[] to Integer[]; this can for instance be done with org.apache.commons.lang.ArrayUtils.toObject()

Christoffer
That will convert it to a List<int> which is not interchangable with List<Integer>
willcodejavaforfood
There is no such thing as a List<int>.
Michael Borgwardt
You can't have a List<int>!
pjp
Oh fair point :)
willcodejavaforfood
This will not work - It will give you a single element List; the element's class being [I (i.e. int[]). Arrays.asList does not deal with auto-boxing and you're better off writing a utility method as described by willcodejavaforfood.
Adamski
@Adamski - Thank you :)
willcodejavaforfood
This is wrong, you'll get back a List<int[]> which isn't what you're after
butterchicken
How come a wrong answer gets so many upvotes ?
Leonel
So use Arrays.toList(ArrayUtils.toObject(int[]));
Christoffer
You should close this answer - you'll get a nice silver badge for it too!
oxbow_lakes
What's ArrayUtils?
Adamski
@Adamski - org.apache.commons.lang.ArrayUtils.toObject()
willcodejavaforfood
It is part of the Apache Commons library (Lang), http://commons.apache.org/.
Kathy Van Stone
+9  A: 

There is no shortcut for converting from int[] to List as Arrays.asList does not deal with boxing and will just create a List which is not what you want. You have to make a utility method.

    int[] ints = {1, 2, 3};
    List<Integer> intList = new ArrayList<Integer>();
    for (int index = 0; index < ints.length; index++)
    {
        intList.add(ints[index]);
    }
willcodejavaforfood
It is best to initialise the list with the size of the array
David Rabinowitz
@David Rabinowitz - Not sure what to say to that :)
willcodejavaforfood
If you insist to use the ArrayList implementation, why not just use the overloaded constructor to do: new ArrayList(myArray) ?
Jørn Schou-Rode
I dont think there is such a constructor
willcodejavaforfood
for (int i : ints) intList.add(i);
Stephen Denne
@willcodejavaforfood - David means that this is better: new ArrayList<Integer>(ints.length);
Stephen Denne
@willcodejavaforfood: declaring the size of the ArrayList when it is being constructed will prevent it having to internally resize after a certain amount is added. Not sure if the benefit is small, but there's definitely a benefit.
Grundlefleck
+6  A: 

It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:

"Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays."

Adamski
+2  A: 

Arrays.asList will not work as some of the other answers expect.

This code will not create a list of 10 integers. It will print 1, not 10:

int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());

This will create a list of integers:

List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

If you already have the array of ints, there is not quick way to convert, you're better off with the loop.

On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:

String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
Leonel
+3  A: 

give a try to this class:

class PrimitiveWrapper<T> extends AbstractList<T> {

    private final T[] data;

    private PrimitiveWrapper(T[] data) {
        this.data = data; // you can clone this array for preventing aliasing
    }

    public static <T> List<T> ofIntegers(int... data) {
        return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
    }

    public static <T> List<T> ofCharacters(char... data) {
        return new PrimitiveWrapper(toBoxedArray(Character.class, data));
    }

    public static <T> List<T> ofDoubles(double... data) {
        return new PrimitiveWrapper(toBoxedArray(Double.class, data));
    }  

    // ditto for byte, float, boolean, long

    private static <T> T[] toBoxedArray(Class<T> boxClass, Object components) {
        final int length = Array.getLength(components);
        Object res = Array.newInstance(boxClass, length);

        for (int i = 0; i < length; i++) {
            Array.set(res, i, Array.get(components, i));
        }

        return (T[]) res;
    }

    @Override
    public T get(int index) {
        return data[index];
    }

    @Override
    public int size() {
        return data.length;
    }
}

testcase:

List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc
dfa
+8  A: 

I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:

    public List<Integer> asList(final int[] is)
    {
            return new AbstractList<Integer>() {
                    public Integer get(int i) { return is[i]; }
                    public int size() { return is.length; }
            };
    }
Christoffer
+1 this is shorter than mine but mine works for all primitives types
dfa
While quicker and using less memory than creating an ArrayList, the trade off is List.add() and List.remove() don't work.
Stephen Denne
I quite like this solution for large arrays with sparse access patterns but for frequently accessed elements it would result in many unnecessary instantiations of Integer (e.g. if you accessed the same element 100 times). Also you would need to define Iterator and wrap the return value in Collections.unmodifiableList.
Adamski
A: 

Integer[] arr1 = {1,2,3}; List list = new ArrayList(); list = Arrays.asList(arr1);

Lists can be formed of only Objects and not primitives.

if you have an int array try converting it to Integer array and further to a list

no need to instantiate a new ArrayList and discard it here
newacct
A: 

The smallest piece of code would be

public List<Integer> myWork(int[] array) {
        return Arrays.asList(ArrayUtils.toObject(array));
}

where ArrayUtils comes from commons-lang :)

Calm Storm
A: 

You can easily do Integer[] to List

    List<Integer> = Arrays.asList(new Integer(4));

I suspect you can then do List = Arrays.asList(4);

(PS-the parameter to the asList method is actually an array, so you can pass in a single element or the array)

Chris Stepnitz
+2  A: 

Also from guava libraries... com.google.common.primitives.Ints:

List<Integer> asList(int...)
louisgab