我在对 ArrayList 使用 haseNext() 方法时遇到此错误:
error: cannot find symbol
while(isduplicate == false && birthdays.hasNext())
这是我的代码:
import java.util.*;
class hello
{
public static void main(String args[])
{
Integer size = 4;
Integer count = 5;
Integer doubleinarray = 0;
for(Integer i = 0 ; i < count ; i++) {
List<Integer> birthdays = new ArrayList<Integer>();
birthdays = CreateSimulator(size);
Integer countdown = size;
boolean isduplicate = false;
while(isduplicate == false && birthdays.hasNext()) {
Integer date = birthdays.get(0);
birthdays.remove(0);
if(birthdays.contains(date)) {
isduplicate = true;
doubleinarray ++;
}
}
}
System.out.println(doubleinarray / count * 100);
}
public static List<Integer> CreateSimulator(int size)
{
List<Integer> Birthdays = new ArrayList<Integer>(size);
Random rand = new Random();
for(Integer i =0 ; i < size ; i++) {
Birthdays.add(rand.nextInt(364) + 1);
}
return Birthdays;
}
}
我不明白为什么它不接受 hasNext。除此之外,其余代码工作正常。
感谢您的帮助
谢谢:)
最佳答案
你必须做这样的事情:
Iterator<Integer> birthdaysIterator = birthdays.iterator();
使用birthDaysIterator
,您可以调用hasNext
。
但现在不推荐这样做。 您最好执行正常操作,例如:
正常情况下:
for (int i = 0; i < birthdays.size(); i++) {
System.out.println(birthdays.get(i));
}
使用 for-each 循环:
for (Integer birthday : birthdays) {
System.out.println(birthday);
}
使用 Java 8 流:
birthdays.forEach((birthday) -> {
System.out.println(birthday);
});
编辑:
根据@OHGODSPIDERS,如果您使用我建议的其他 3 个版本,您将遇到 ConcurrentModificationException 。为了避免这种情况,您可以坚持使用迭代器,也可以使用中间列表来保留要删除的元素,然后将它们全部删除。
示例:
List<String> toRemove = new ArrayList<>();
for (String birthday : birthdays) {
if (someCondition) {
toRemove.add(birthday);
}
}
birthdays.removeAll(toRemove);
关于Java - 使用 hasNext() 方法时出现 "cannot find symbol"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47051006/