【问题标题】:How to compare the previous index with current index on run time in ArrayList如何在 ArrayList 中将前一个索引与当前索引进行比较
【发布时间】:2018-04-15 18:51:48
【问题描述】:

我正在检查 ArrayList 的先前索引与当前索引具有相同值的运行时间。如果先前的值与当前值的比较值相同,那么我不想再次添加到列表中。我怎样才能做到这一点?请在下面找到我一直在尝试的代码:

List<EventDto> liveEvents = new ArrayList<EventDto>();
EventDto liveTvEventDto = null;
List<CustomerEventDetails> customerDetails = odsRepository.getEventDetails(countryCode, customerId);        
if (customerDetails.size() > 0) {           
    for (CustomerEventDetails customerData : customerDetails) {
        liveTvEventDto = new EventDto();
        liveTvEventDto.setCountryCode(customerData.getCountryCode());
        liveTvEventDto.setCustomerId(customerData.getCustomerId());

        ListIterator<EventDto> listIterator =  liveEvents.listIterator();

        if (listIterator.previousIndex() == -1) {
            listIterator.next();    

            int i =listIterator.previousIndex();
            System.out.println("listIterator:"+liveEvents.get(i));
            if (!(StringUtility.trimmedOrEmptyIfNull(liveEvents.get(i).getCustomerId()).equals(StringUtility.trimmedOrEmptyIfNull(liveTvEventDto.getCustomerId()))
                                && StringUtility.trimmedOrEmptyIfNull(liveEvents.get(i).getCountryCode()).equals(StringUtility.trimmedOrEmptyIfNull(liveTvEventDto.getCountryCode()))))
                liveEvents.add(liveTvEventDto);
        }
    }                       
}

【问题讨论】:

  • 为什么不使用普通循环而不是增强的 for 循环?
  • 我怎样才能使用那个循环?
  • 我添加了一个答案。看看有没有帮助。

标签: java for-loop arraylist iterator listiterator


【解决方案1】:

我认为您不需要在内部使用迭代器。只需使用size() 方法获取最后一个索引即可。

for (CustomerEventDetails customerData : customerDetails) {
    liveTvEventDto = new EventDto();
    // Set member variables

    if (liveEvents.size() > 0) {
        System.out.println("Last Object: " + liveEvents.get(liveEvents.size() - 1));

        if (/* Logic for checking if the objects are NOT equal */)
            liveEvents.add(liveTvEventDto);
    } else {
        liveEvents.add(liveTvEventDto);
    }
}

注意:您可以在对象的equals() 方法中使用具有相等逻辑的HashSet,而不是使用ArrayList

【讨论】:

  • 你能举出这个代码的例子吗?
  • 抱歉更新。使用对象的equals() 方法。这似乎是一个很好的例子 -> programcreek.com/2013/09/…
  • 在将其添加到列表之前,大小如何大于 0 :) if (liveEvents.size() > 0) { System.out.println("Last Object: " + liveEvents.get( liveEvents.size() - 1)); if (/* 检查对象是否不相等的逻辑 */) liveEvents.add(liveTvEventDto); }
  • 我的错。只需添加另一个添加到列表中的 else 块。
猜你喜欢
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
相关资源
最近更新 更多