写在前面的话:读书破万卷,编码如有神
--------------------------------------------------------------------
下文主要对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

内功心法 -- java.util.ArrayList<E> (5)的更多相关文章

  1. 内功心法 -- java.util.ArrayList<E> (1)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...

  2. 内功心法 -- java.util.ArrayList<E> (2)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...

  3. 内功心法 -- java.util.ArrayList<E> (3)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...

  4. 内功心法 -- java.util.ArrayList<E> (4)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...

  5. 内功心法 -- java.util.ArrayList<E> (6)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...

  6. 解决springmvc报No converter found for return value of type: class java.util.ArrayList问题

    一.背景 最近闲来无事,想自己搭建一套Spring+SpringMVC+Mybatis+Mysql的环境(搭建步骤会在以后博客中给出),结果运行程序时,适用@ResponseBody注解进行返回Lis ...

  7. Java.util.ArrayList详解

    java.util.ArrayList就是传说中的动态数组. 继承了关系,有此可看出ArrayList与list的collection的关系 public class ArrayList<E&g ...

  8. java@ 利用ArrayList实现dijkstra算法以及topological 排序算法(java.util.ArrayList)

    package dataStructure; import java.util.ArrayList; import java.util.LinkedList; import java.util.Que ...

  9. java.util.ArrayList、java.util.vector和java.util.LinkedList (JDK 1.8.0_111)

    一.java.util.ArrayList 1.1 ArrayList 继承结构 ArrayList实现了RandomAccess,可以随机访问(其实就是通过数组下标访问):实现了Cloneable, ...

随机推荐

  1. Python正则表达式学习笔记

    [] 字符类,只要匹配里面的任意字符,都算匹配 . 元字符,可以匹配除换行符之外的所有字符 大小写敏感,但是可以关闭 \d  可以匹配0-9中的任意数字 {3}大括号里面的数字,边上前面一个字符匹配的 ...

  2. 使用msm文件创建msi

    一.不使用merge module的ModuleSubstitution和ModuleConfiguration 1.创建MyMsm.msm <?xml version="1.0&qu ...

  3. (总结)Linux的chattr与lsattr命令详解

    PS:有时候你发现用root权限都不能修改某个文件,大部分原因是曾经用chattr命令锁定该文件了.chattr命令的作用很大,其中一些功能是由Linux内核版本来支持的,不过现在生产绝大部分跑的li ...

  4. (简单) POJ 1426 Find The Multiple,BFS+同余。

    Description Given a positive integer n, write a program to find out a nonzero multiple m of n whose ...

  5. #Pragma Pack(n)与内存分配

    #pragma pack(n) 解释一: 每个特定平台上的编译器都有自己的默认"对齐系数"(也叫对齐模数).程序员可以通过预编译命令#pragma pack(n),n=1,2,4, ...

  6. (中等) UESTC 360 Another LCIS ,线段树+区间更新。

    Description: For a sequence S1,S2,⋯,SN, and a pair of integers (i,j), if 1≤i≤j≤N and Si<Si+1<S ...

  7. LPC1788的IIC使用

    #ifndef __IIC0_H_ #define __IIC0_H_ #include "common.h" #include "delay.h" //IIC ...

  8. S3C2440看门狗解析

    个PCLK周期的复位信号 也就是说,在某些环境下,看门狗可以当做定时器使用,当他中断的时候并不发生复位,只发生中断,我看看图 看门狗的中断和复位信号是可以依靠wtcon来切断的(看门狗的时钟是无法切断 ...

  9. SQL Server 2012 - 数据表的操作

     unicode:双字节编码      variable:可变的    character:字符 T-SQL:  Transact Structured Query Language unique:唯 ...

  10. X-001 FriendlyARM Tiny4412 uboot移植前奏

    版权声明:本文为博主原创文章,转载请注明出处 开发环境:win7 64位 + VMware12 + Ubuntu14.04 64位 工具链:linaro提供的gcc-linaro-6.1.1-2016 ...