我正在尝试创建一个方法来创建给定数字的素因子列表,然后在数组中返回它们。除了将 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
此外,我不确定如何接收返回的数组,所以我也需要一些帮助。谢谢!