简体   繁体   中英

adding item during iteration in java special usecase

I've got a function that should return a list of dates ( java.sql.Date ) based within a range set as startDate - endDate . I first added the startDate and want to increment it (either +1 day, week or month), and then keep going from the "newest" date until reaching the endDate.

I've tried using a traditional foreach which does not work as it doesn't allow adding new dates while iterating, so I switched to ListIterator . This only goes into while once, increments the date, adds it but then apparently doesn't have a next because the add function doesn't append the item at the end(?)

What would be a practical way to solve this task?

public List<Date> getBookingDatesInRange(Date startDate, Date endDate, boolean isDaily, boolean isWeekly) {

    List<Date> dates = new ArrayList<Date>();
    dates.add(startDate);
    ListIterator<Date> iter = dates.listIterator();         
    while(iter.hasNext()) {
        LocalDate new = iter.next().toLocalDate();
        Date newDate;
        if(isDaily) {
            newDate= Date.valueOf(new.plusDays(1));
        } else if(isWeekly) {
            newDate= Date.valueOf(new.plusWeeks(1));
        } else {
            newDate= Date.valueOf(new.plusMonths(1));
        }
        if(newDate.before(endDate) || newDate.equals(endDate) {
            iter.add(newDate);
        } else {
            return dates;
    }                   
}

Why do you want to do the while loop based on an Iterator? Would it not be more logical to base it on just the date check you do during the iteration?

  public static List<Date> getBookingDatesInRange(Date startDate, Date endDate, boolean isDaily, boolean isWeekly) {

  List<Date> dates = new ArrayList<>();
  dates.add(startDate);
  Date newDate = startDate;
  while(newDate.before(endDate) || newDate.equals(endDate)) {

    if(isDaily) {
       newDate = Date.valueOf(newDate.toLocalDate().plusDays(1));
    } else if(isWeekly) {
         newDate = Date.valueOf(newDate.toLocalDate().plusWeeks(1));
    } else {
      newDate = Date.valueOf(newDate.toLocalDate().plusMonths(1));
    }
    dates.add(newDate);
    }
  }
  return dates;
}

添加新项时使用ListIterator::nextIndex() ,然后将迭代器变量重置为ArrayList::listIterator(int index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM