内功心法 -- java.util.ArrayList (5)

写在前面的话:读书破万卷,编码如有神
--------------------------------------------------------------------
下文主要对java.util.ArrayList<E>中的Iterator和List操作进行介绍,主要内容包括:

1、ArrayList的Iterator和ListIterator操作

2、ArrayList的subList操作

参考内容:

1、JDK源码(1.7)

-------------------------------------------------------------------- 

1. ArrayList的Iterator和List操作                                                                         

Iterator和子List操作

关于Iterator操作这里涉及到"迭代器模式",可以简单看看

(1)Iterator<E> iterator()

功能: 返回列表的Iterator实例

示例代码:

 import java.util.ArrayList;
import java.util.Iterator; public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(22);
list.add(33);
list.add(44);
list.add(11);
list.add(15);
list.add(12);
list.add(7);
list.add(3);
System.out.println("list1 :" + list);
//测试ArrayList的'Iterator<E> iterator()'方法的使用
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
System.out.print(it.next() +" ");
}
System.out.println("");
System.out.println("list2 :" + list);
it.remove();
System.out.println("list3 :" + list);
}
} 运行结果:
list1 :[22, 33, 44, 11, 15, 12, 7, 3]
22 33 44 11 15 12 7 3
list2 :[22, 33, 44, 11, 15, 12, 7, 3]
list3 :[22, 33, 44, 11, 15, 12, 7]

源代码如下:(这个方法直接用了一个内部类来帮助实现功能)

     public Iterator<E> iterator() {
//每次调用iterator()方法都会去new一个Itr类
return new Itr();
}
     private class Itr implements Iterator<E> {
//下一个返回元素的索引
int cursor; // index of next element to return
//最近返回元素的索引
int lastRet = -1; // index of last element returned; -1 if no such
//fast-fail标记标识
int expectedModCount = modCount; //如果列表仍有元素可以迭代,则返回true
public boolean hasNext() {
return cursor != size;
} //返回迭代的下一个元素
@SuppressWarnings("unchecked")
public E next() {
//检查fast-fail机制
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
//从迭代器指向的列表中移除迭代器返回的最后一个元素
public void remove() {
//检查迭代器是否返回过元素
if (lastRet < 0)
throw new IllegalStateException();
//检查fast-fail机制
checkForComodification(); try {
//删除列表中最后返回的那个元素
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
} //检查fast-fail机制标识
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

(2)ListIterator<E> listIterator()

功能: 返回列表的ListIterator实例

源代码如下:(这个方法直接用了一个内部类来帮助实现功能)

 public ListIterator<E> listIterator() {
return new ListItr(0);
}

(3)ListIterator<E> listIterator(int index)

功能: 返回列表的ListIterator实例

源代码如下:(这个方法直接用了一个内部类来帮助实现功能)

     public ListIterator<E> listIterator(int index) {
//首先检查index是否合法,如果不合法则抛出异常
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
//创建一个ListItr对象
return new ListItr(index);
}
     private class ListItr extends Itr implements ListIterator<E> {
/*带参数构造函数*/
ListItr(int index) {
super();
cursor = index;
}
//如果以逆向遍历列表,列表迭代器有多个元素,则返回true
public boolean hasPrevious() {
return cursor != 0;
}
//返回对next的后续调用所返回的元素的索引
public int nextIndex() {
return cursor;
}
//返回对previous的后续调用所返回元素的索引
public int previousIndex() {
return cursor - 1;
}
//返回列表中前一个元素
@SuppressWarnings("unchecked")
public E previous() {
//检查fast-fail机制标识
checkForComodification();
//返回索引下标值减1
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
//返回元素
return (E) elementData[lastRet = i];
}
//用指定元素替换next或者previous返回的最后一个元素
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
//检查fast-fail机制
checkForComodification(); try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//将指定的元素插入列表
public void add(E e) {
//检查fast-fail机制
checkForComodification(); try {
int i = cursor;
//添加元素e到计划中
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}

(4)List<E> subList(int fromIndex, int toIndex)

功能: 返回列表从索引位置fromIndex到toIndex之间元素组成的子列表

源代码如下:

 public List<E> subList(int fromIndex, int toIndex) {
//检查参数fromIndex和toIndex是否合法
subListRangeCheck(fromIndex, toIndex, size);
//创建一个SubList对象
return new SubList(this, 0, fromIndex, toIndex);
} static void subListRangeCheck(int fromIndex, int toIndex, int size) {
//起始位置fromIndex小于0,则抛出异常
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
//终止位置toIndex大于列表中元素个数size,则抛出异常
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
//起始位置fromIndex 大于 终止位置toIndex,则抛出异常
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +") > toIndex(" + toIndex + ")");
} /*
内部类,为了配合subList方法
*/
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
//构造方法
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
} public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
} public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
} public int size() {
checkForComodification();
return this.size;
} public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
} public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
} protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
} public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
} public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false; checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
} public Iterator<E> iterator() {
return listIterator();
} public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset; return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = ArrayList.this.modCount; public boolean hasNext() {
return cursor != SubList.this.size;
} @SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= SubList.this.size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
} public boolean hasPrevious() {
return cursor != 0;
} @SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = i)];
} public int nextIndex() {
return cursor;
} public int previousIndex() {
return cursor - 1;
} public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification(); try {
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
} public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification(); try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
} public void add(E e) {
checkForComodification(); try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
} final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
} public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
} private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
} private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
}

-------------------------------------------------------------------------------

java.util.ArrayList系列文章

java.util.ArrayList<E>(1)  java.util.ArrayList<E>(2)  java.util.ArrayList<E>(3)

java.util.ArrayList<E>(4)  java.util.ArrayList<E>(5)  java.util.ArrayList<E>(6)

相关知识                                                                                              

java.util.Collection<E>   java.util.AbstractCollection<E>   java.util.List<E>

java.util.AbstractList<E>   java.util.Iterator<E>   java.util.ListIterator<E>

Java中的标记接口   迭代器模式   Java中的深拷贝和浅拷贝  java.util.Arrays

上一篇:九宫格抽奖HTML+JS版


下一篇:【javascript】九宫格抽奖组件设计