我试图创建一个方法来创建一个给定数字的素数因子列表,然后将它们返回到一个数组中。除了将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