有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将ArrayList转换为数组,然后用Java返回它?

我试图创建一个方法,创建一个给定数字的素因子列表,然后以数组的形式返回它们。除了将ArrayList转换为数组之外,其他一切似乎都很正常。此外,我不确定是否正确返回了数组

这是我的密码

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;

当我编译

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

此外,我不确定如何接收返回的数组,所以我也需要一些帮助。谢谢


共 (2) 个答案

  1. # 1 楼答案

    将int[]数组更改为整数[]

    static Integer[] listOfPrimes(int num) {
        List<Integer> primeList = new ArrayList<Integer>();
        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;
            }
        }
    
        return primeList.toArray(new Integer[0]);
    }
    
  2. # 2 楼答案

    int[] primeArray = primeList.toArray(new int[primeList.size()]);
    

    但是我对用int比用Integer更能做到这一点没有信心