java – ArrayList warning- warning:[unchecked]未选中调用add
发布时间:2020-12-14 05:09:20 所属栏目:Java 来源:网络整理
导读:我一直试图让这段代码在这个阶段感觉像一个时代一样.它是为了计算一个范围内的素数,并且我已经写了一个打印它们的方法.不幸的是,代码不会编译,引用警告: “warning:[unchecked]未选中调用add(E)作为原始类型的成员java.util.List” – 我从谷歌搜索中了解
我一直试图让这段代码在这个阶段感觉像一个时代一样.它是为了计算一个范围内的素数,并且我已经写了一个打印它们的方法.不幸的是,代码不会编译,引用警告:
“warning:[unchecked]未选中调用add(E)作为原始类型的成员java.util.List” – 我从谷歌搜索中了解到,这个警告是为了不声明在你的错误中应该有什么类型的值,但是我已经做到了,只有当我尝试使用.add()函数数组列表. 当我尝试运行它时,会给出一个更可怕的错误 我觉得我在这一点上已经失明了,尽管有几次尝试找不到我做错了什么.有没有人可以散发一些光?非常感谢. 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循环作为替代方法: public void print() { int i = 1; for (Integer nextPrime:listOfPrimeNumbers) { System.out.println("the " + i + "th prime is: " + nextPrime); i++; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |