2013-10-18 44 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]); 
} 
相关问题