Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java arraylist cannot find constructor, using arrays.aslist

I'm using the Arrays.asList().contains() method in my code, as shown in the top answer: How can I test if an array contains a certain value?, so I am going to use Arrays.asList() in the code.

However, the compiler rejects this following code. Is it because of using primitives for my primes array, rather than a reference type? I don't think so, due to autoboxing, but I just wanted to check.

import java.math.*;
import java.util.ArrayList;
import java.util.Arrays;

public class .... {
    public static void main(String[] args) {
        int[] primes = formPrimes(15);
        ArrayList<Integer> primes1 = new ArrayList<Integer>(Arrays.asList(primes));
        // Rest of code...
    }

    public static int[] formPrimes(int n) {
        // Code that returns an array of integers
    }
}

I get one error, a cannot find symbol error.

symbol : constructor ArrayList(java.util.List)

location: class java.util.ArrayList ArrayList primes1 = new ArrayList(Arrays.asList(primes));

Basically, I've got a function returning an array of integers, and I want to convert it into an array list, and I'm running into trouble with using the ArrayList constructor.

like image 619
user16647 Avatar asked Jun 01 '12 23:06

user16647


1 Answers

Yes. Autoboxing does not apply to arrays, only to primitives.

The error I get in eclipse is The constructor ArrayList<Integer>(List<int[]>) is undefined

Thats because the constructor in ArrayList is defined as public ArrayList(Collection<? extends E> c). As you can see, it only accepts a subtype of Collection, which int is not.

Just change your code to:

public class .... {
    public static void main(String[] args) {
        Integer[] primes = formPrimes(15);
        ArrayList<Integer> primes1 = new ArrayList<Integer>(Arrays.asList(primes));
        // Rest of code...
    }

    public static Integer[] formPrimes(int n) {
        // Code that returns an array of integers
    }
}

and all should be well, assuming you return an Integer array from fromPrimes.

Update From Andrew's comments, and after peeking into the source of Arrays.asList:

public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

So what is really happening here is that Arrays.asList(new int[] {}) would actually return a List<int[]>, unlike Arrays.asList(new Integer[] {}) which would return aList<Integer>. Obviously the ArrayList constructor will not accept a List<int[]>, and hence the compiler complains.

like image 154
Jeshurun Avatar answered Nov 13 '22 11:11

Jeshurun