Yev*_*ago 0 java iterator while-loop
我有以下while循环,如果我在while循环条件中放入this.boatTripsList.iterator().hasNext(),则抛出错误.当我创建迭代器然后放入while循环条件时,它将工作.为什么是这样?感谢和问候.(第二个版本抛出错误)
public Journey(List<BoatTrip> trips) {
this.boatTripsList = new LinkedList<BoatTrip>();
Iterator<BoatTrip> iterator = trips.iterator();
//add the given boat trips to the boattrips list
while (iterator.hasNext()) {
BoatTrip thistrip = iterator.next();
this.boatTripsList.add(thistrip);
}
}
public Journey(List<BoatTrip> trips) {
this.boatTripsList = new LinkedList<BoatTrip>();
//add the given boat trips to the boattrips list
while (trips.iterator().hasNext()) {
BoatTrip thistrip = iterator.next();
this.boatTripsList.add(thistrip);
}
}
Run Code Online (Sandbox Code Playgroud)
fge*_*fge 13
这是正常的:如果您的while条件是while(trips.iterator().hasNext()),则每次都创建一个新的迭代器.如果您的列表不为空,那么条件将始终为真......
在循环本身中,你使用你在进入循环之前创建的迭代器...结果,NoSuchElementException当这个迭代器为空时你会得到一个.
使用:
final Iterator<Whatever> = list.iterator();
Whatever whatever;
while (iterator.hasNext()) {
whatever = iterator.next();
// do whatever stuff
}
Run Code Online (Sandbox Code Playgroud)
但对于步行列表,首选的是foreach循环:
for (final BoatTrip trip: tripList)
// do whatever is needed
Run Code Online (Sandbox Code Playgroud)
如果要将列表的内容添加到另一个列表,请使用.addAll():
// no need for the "this" qualifier, there is no name conflict
boatTripList.addAll(trips);
Run Code Online (Sandbox Code Playgroud)