java while (LinkedList.iterator().hasNext()) 不起作用



我有以下 while 循环,如果我把 this.boatTripsList.iterator((.hasNext(( 放在 while 循环条件中,它会抛出错误。当我创建迭代器然后放入 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);
    }
}
这是

正常的:如果你的while条件是while(trips.iterator().hasNext()),你每次都会创建一个新的迭代器。如果您的列表不为空,则条件将始终为真...

在循环本身中,您可以使用在进入循环之前创建的迭代器...因此,当此迭代器为空时,您将获得一个NoSuchElementException

用:

final Iterator<Whatever> = list.iterator();
Whatever whatever;
while (iterator.hasNext()) {
     whatever = iterator.next();
     // do whatever stuff
}

但对于步行列表,首选 foreach 循环:

for (final BoatTrip trip: tripList)
    // do whatever is needed

如果要将列表的内容添加到另一个列表,请使用 .addAll()

// no need for the "this" qualifier, there is no name conflict
boatTripList.addAll(trips);

您没有使用您在代码第一行请求的iterator - 您每次都在请求一个新的,所以它总是有下一个。

对 .iterator(( 的调用会获得一个新的迭代器。如果在循环中执行此操作,您将始终获得新的迭代器,而不是迭代现有的迭代器。

this.boatTripsList.iterator((.hasNext(( 是错误的

this.boatTripsList.hasNext(( 是正确的

最新更新