// 获取迭代器
Iterator<List<Integer>> iterator = partition.iterator();
// 源码分析调用 List 中的 iterator() 方法// java.util.List/**
* Returns an iterator over the elements in this list in proper sequence.
*
* @return an iterator over the elements in this list in proper sequence
*/
Iterator<E> iterator();
// java.util.AbstractList implements List 具体实现在 AbstractList 类中
public Iterator<E> iterator() {
returnnew Itr(); // List 中的内部类
}
privateclassItrimplementsIterator<E> {/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;
public boolean hasNext() { // 集合中是否有下一个元素return cursor != size();
}
public E next() { // 获取集合中的下一个元素
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
thrownew NoSuchElementException();
}
}
}
// 集合中是否有下一个元素,需要调用 size() 方法// 获取集合中的下一个元素,需要调用 get(i) 方法// 两个方法都是 AbstractList 抽象方法,具体实现由子类完成abstract public E get(int index);
// Lists 类中 Partition 继承 AbstractList 实现具体的方法private static classPartition<T> extendsAbstractList<List<T>> {final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
public List<T> get(int index) {
Preconditions.checkElementIndex(index, this.size());
int start = index * this.size;
int end = Math.min(start + this.size, this.list.size());
returnthis.list.subList(start, end);
}
public int size() {
return IntMath.divide(this.list.size(), this.size, RoundingMode.CEILING);
}
public boolean isEmpty() {
returnthis.list.isEmpty();
}
}
- 从源码实现上Partition并没有对List<T>进行分组分片的操作,而是等遍历使用集合的时,通过Iterator 循环时每次调用 Partition 类内部的 size 方法确认分组后的集合的大小,调用 get 方法通过定位每个分组内元素的起始、截止位置调用 subList 进行截取
- for 循环调用等价于 Iterator 调用