Java 中 List.subList() 的应用

List.subList(int fromIndex,int toIndex)

注意:

  • fromIndex 从0起
  • toIndex 为20时,取的是到19为止,即(0,20)取的是0,1......18,19
  • fromIndex/toIndex 大于 list.size() 时会报错,所以必须判断索引值是否溢出
      fromLine = fromLine + subListLength;
      if (toLine + subListLength > targetList.size()) {
        toLine = targetList.size();
      } else {
        toLine = toLine + subListLength;
      }

实践

//targetList
int pageIndex = 1;
int pageSize = 20;
int pageCount =
      targetList.size() % pageSize == 0
            ? targetList.size() / pageSize
            : targetList.size() / pageSize + 1;

while (pageIndex <= pageCount) {
  // 当前批次的起止item 
  int from =(pageIndex - 1) * pageSize+1;
  int to = pageIndex == pageCount ? targetList.size() : pageIndex * pageSize;
  
  targetList.subList(from,to);      
  
  // 下一批次
  pageIndex = pageIndex + 1;
    }

你可能感兴趣的:(java)