如何将ArrayList转换为数组,然后用Java返回它?
我试图创建一个方法,创建一个给定数字的素因子列表,然后以数组的形式返回它们。除了将ArrayList转换为数组之外,其他一切似乎都很正常。此外,我不确定是否正确返回了数组
这是我的密码
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 楼答案
将int[]数组更改为整数[]
# 2 楼答案
但是我对用
int
比用Integer
更能做到这一点没有信心