ArrayList警告-警告:[unchecked]对add(E)的未经检查的调用,也不会运行文件
问题内容:
我一直在尝试使此代码在这个阶段适合年龄。它的目的是计算一个范围内的素数,我已经编写了一种打印它们的方法。不幸的是,该代码由于警告而无法编译:
“警告:[未经检查]以未经检查的方式将add(E)作为原始类型java.util.List的成员进行调用”
-我从谷歌搜索中了解到,该警告不是为了声明您应该输入哪种类型的值,但是我已经这样做了,并且该错误似乎仅在尝试在我的.add()函数上出现数组列表。
而当我尝试运行它时,它会给出一些更为可怕的错误,即“静态错误:未定义名称’PrimeNumbers’
我认为我在这一点上一直是代码盲的,尽管有几次尝试都无法找出我在做什么错。
import java.util.*;
public class PrimeNumbers {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumbers primeNumberList = new PrimeNumbers(50);
primeNumberList.print(); //use our new print method
}
public PrimeNumbers (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
public void print() //add this printout function
{
int i = 1;
Iterator iterator = listOfPrimeNumbers.listIterator();
while (iterator.hasNext())
{
System.out.println("the " + i + "th prime is: " + iterator.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
问题答案:
更改此行
private List listOfPrimeNumbers; //add a member variable for the ArrayList
至
private List<Integer> listOfPrimeNumbers; //add a member variable for the ArrayList
这将消除警告。
奖励 -您可能想在方法内部使用 增强的for循环print
作为替代方法:
public void print() {
int i = 1;
for (Integer nextPrime:listOfPrimeNumbers) {
System.out.println("the " + i + "th prime is: " + nextPrime);
i++;
}
}