2013-10-18 45 views
1

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

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

+1

可能重複[如何將包含整數的ArrayList轉換爲原始int數組?](http://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array) –

+1

Java集合只能保存對象。 int是一個原始數據類型,例如不能存放在ArrayList中。你需要使用Integer來代替。 http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java – muthu

+0

你使用IDE,如Netbeans,IntelliJ或Eclipse? – reporter

回答

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

,但我真的不相信能夠如果您想使用泛型toArray()int做到這一點比Integer

+3

不,這不起作用 –

7

,你需要使用Integer包裝類代替原始類型爲int

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

編譯器給人的錯誤是,說明你要調用的方法(List#toArray(T[]))並不適用於int[]類型的參數,只是因爲int不是Object(這是基本類型)。 IntegerObject然而,包裝int(這是Integer類存在的主要原因之一)。

當然,您也可以手動遍歷List,並將數組中的Integer添加爲int

這裏有一個相關的問題上SO:How to convert List to int[] in Java?,有很多其他的建議(Apache的公地,番石榴,...)

+0

非常感謝!我完全沒有意識到int和Integer是有區別的。 – SadBlobfish

+0

歡迎來到StackOverflow!很高興這有幫助。請記住點贊回答有用的答案,並接受你認爲更好地回答你的問題的答案(參見[接受答案如何工作?](http://meta.stackexchange.com/q/5234/169503))。這將有助於未來訪問此問題的其他人。 –

0

變化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]); 
} 
相關問題