Java arraylist使用arrays.aslist找不到构造函数

use*_*647 8 java arrays generics arraylist

我在我的代码中使用了Arrays.asList().contains()方法,如上面的答案所示:如何测试数组是否包含某个值?,所以我将在代码中使用Arrays.asList().

但是,编译器拒绝以下代码.是因为我的素数数组使用原语而不是引用类型?由于自动装箱,我不这么认为,但我只想查一下.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,找不到符号错误.

symbol:构造函数ArrayList(java.util.List)

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

基本上,我有一个函数返回一个整数数组,我想将它转换为数组列表,我使用ArrayList构造函数遇到了麻烦.

Jes*_*run 9

是.自动装箱不适用于数组,仅适用于基元.

我在日食中遇到的错误是 The constructor ArrayList<Integer>(List<int[]>) is undefined

那是因为ArrayList中的构造函数被定义为public ArrayList(Collection<? extends E> c).如您所见,它只接受Collection的子类型,而int不是.

只需将您的代码更改为:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

假设你从中返回一个Integer数组,那么一切都应该没问题fromPrimes.

从Andrew的评论更新,并在窥视Arrays.asList的源代码后:

public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}
Run Code Online (Sandbox Code Playgroud)

所以这里真正发生的是Arrays.asList(new int[] {})实际上会返回一个List<int[]>,不像那样Arrays.asList(new Integer[] {})会返回一个List<Integer>.显然,ArrayList构造函数不会接受a List<int[]>,因此编译器会抱怨.