写在前面的话:读书破万卷,编码如有神
--------------------------------------------------------------------
下文主要对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. WEB前端资源集(一)

    做前端已经一年了,开发中换过很多开发工具,遇到bug到处求解,以及自学时到处找相关文章及教程,所以经过这么多的风波,我总结了一些对大家有帮助的网站,主题也将长期更新. 资源网站篇 CSDN:全球最大中 ...

  2. Android之事件分发

    网上总结的很详细了,有时间总结下做个笔记

  3. CABasicAnimation 基本动画

    几个可以用来实现热门APP应用PATH中menu效果的几个方法 +(CABasicAnimation *)opacityForever_Animation:(float)time //永久闪烁的动画 ...

  4. “canvas画布仿window系统自带画图软件"项目的思考

    "canvas画布仿window系统自带画图软件"项目的思考 首先贴上DEMO图,并没有美化效果.对UI有要求的,请自带补脑技术. 思考一 在做项目的过程中,我发现"工具 ...

  5. python内置函数all使用的坑

    在代码的改造过程中,因为忽略了一个问题导致数据异常,在改造的过程中以及后续的review中都没注意到这个问题,单元测试也没有覆盖到,记录如下.这个坑在于all的使用上,如果参数为空元组或空列表时,返回 ...

  6. Excel每隔10行取得一个数字

    index(a:a,row(a1)*10) 然后下拉 将一列数字分为好多列 =OFFSET($B$1,(ROW(A1)-1)*11+COLUMN(A1)-1,,) row()返回当前的行,比如A则返回 ...

  7. IO文件

    在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常. Separator: 比如说要在te ...

  8. CentOS 7 上面安装PowerShell

    看了文章 爱上PowerShell , 就想在CentOS 7上面试试PowerShell , 本文记录了在CentOS 7.2上安装Powershell 的过程. 首先我们要从github上下载最新 ...

  9. SVN和Git的一些用法总结

    (A)SVN (1)查看日志提交的时候一般会写上注释,如果要查看提交日志,用以下命令: 1 svn log -l 4 其中,-l 4表示只查看最近4条日志(也可以没有这样的参数,就表示查看所有日志). ...

  10. Angular - - ngHref、ngSrc、ngCopy/ngCut/ngPaste

    ngHref 在Angular程序没完成改变链接上用{{hash}}方式绑定的href值的时候,当用户点击该链接会跳到一个错误的页面. 格式:ng-href=”value” value:表达式. 使用 ...