簡體   English   中英

如何將ArrayList轉換為Array然后在Java中返回?

[英]How do I convert an ArrayList to an Array then return it in Java?

我正在嘗試創建一個方法來創建給定數字的素因子列表,然后將它們返回到數組中。 除了將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;

它在我編譯時返回此錯誤消息...

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

另外,我不知道如何接收返回的數組,所以我也需要一些幫助。 謝謝!

如果要使用通用的toArray()方法,則需要使用Integer包裝類而不是基本類型int

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

編譯器給出的錯誤是聲明要調用的方法( List#toArray(T[]) )不適用於int[]類型的參數,只是因為int不是Object (它是一個原始類型)。 然而, Integer 一個Object ,包裝一個int (這是Integer類存在的主要原因之一)。

當然,您也可以手動迭代List並將其中的Integer元素作為int添加到數組中。

這里有一個相關的問題: 如何在Java中將List轉換為int []? 有很多其他建議(Apache commons,guava,...)

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

但我對使用int不是使用Integer能夠做到這一點並不是很有信心

將int []數組更改為Integer []

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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM