如何将ArrayList转换为Array然后在Java中返回?

Sad*_*ish 2 java arrays arraylist

我正在尝试创建一个方法来创建给定数字的素因子列表,然后将它们返回到数组中.除了将ArrayList转换为Array之外,一切似乎都能正常工作.另外,我不确定我是否正确返回数组.

这是我的代码......

static int[] listOfPrimes(int num) {
    ArrayList primeList = new ArrayList();
    int count = 2;
    int factNum = 0;

    // Lists all primes factors.
    while(count*count<num) {
        if(num%count==0) {
            num /= count;
            primeList.add(count);
            factNum++;
        } else {
            if(count==2) count++;
            else count += 2;
    }
}
int[] primeArray = new int[primeList.size()];
primeList.toArray(primeArray);
return primeArray;
Run Code Online (Sandbox Code Playgroud)

它在我编译时返回此错误消息...

D:\JAVA>javac DivisorNumber.java
DivisorNumber.java:29: error: no suitable method found for toArray(int[])
            primeList.toArray(primeArray);
                     ^
method ArrayList.toArray(Object[]) is not applicable
  (actual argument int[] cannot be converted to Object[] by method invocatio
n conversion)
method ArrayList.toArray() is not applicable
  (actual and formal argument lists differ in length)
Note: DivisorNumber.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
Run Code Online (Sandbox Code Playgroud)

另外,我不知道如何接收返回的数组,所以我也需要一些帮助.谢谢!

Xav*_*ica 8

如果要使用generified toArray()方法,则需要使用Integer包装类而不是基本类型int.

Integer[] primeArray = new Integer[primeList.size()];
primeList.toArray(primeArray);
Run Code Online (Sandbox Code Playgroud)

编译器给出的错误是声明要调用的方法(List#toArray(T[]))不适用于类型的参数int[],只是因为int它不是Object(它是基本类型).然而,an Integer 一个Object包装int(这是Integer该类存在的主要原因之一).

当然,您也可以List手动迭代并将其中的Integer元素添加为int数组中的s.

这里有一个相关的问题:如何在Java中将List转换为int []?有很多其他建议(Apache commons,guava,...)