我試圖創建一個方法來創建一個給定數字的素數因子列表,然後將它們返回到一個數組中。除了將ArrayList轉換爲數組之外,似乎一切正常。另外,我不確定是否正確返回數組。如何將ArrayList轉換爲數組然後使用Java返回?
這裏是我的代碼...
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
另外,我不知道如何接收返回的數組,所以我也需要一些幫助。謝謝!
可能重複[如何將包含整數的ArrayList轉換爲原始int數組?](http://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array) –
Java集合只能保存對象。 int是一個原始數據類型,例如不能存放在ArrayList中。你需要使用Integer來代替。 http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java – muthu
你使用IDE,如Netbeans,IntelliJ或Eclipse? – reporter