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

    tar jxvf jemalloc-3.5.1.tar.bz2 cd jemalloc-3.5.1 ./configure make && make install echo '/us ...

  2. iOS探究UITableView的内部代码,仿UITableView自定义

    大家都知道UITableView,最经典在于循环利用,这里我自己模仿UITableView循环利用,写了一套自己的TableView实现方案,希望大家看了我的文章,循环利用思想有显著提升. 研究UIT ...

  3. HTML5 - Canvas动画样例(谷歌弹跳球)

    1,样例说明 (1)在没有鼠标介入的情况下,这些球就像有磁性一样拼成"Google"字样. (2)在鼠标移动到其中后,小球像是受到了排斥,向画布的四周扩散,然后不规则地反弹回来. ...

  4. USB那点事3 -使用端口2作为custom HID的传输(转)

    源:USB那点事3 -使用端口2作为custom HID的传输 USB custom HID例子中是使用了端口1作为通信,那么现在我使用端口2作为通信端了,该如何修改呢?如下所示: 首先修改:usb_ ...

  5. UIAlertController高级之嵌入其他控件 分类: ios技术 2015-02-02 11:58 96人阅读 评论(0) 收藏

    在编码过程中,我们经常遇到需要这样一个效果,就是弹出框的嵌套; 举个最简单的例子,比如你要选择时间,必然需要一个时间选择器DatePicker.但是这个选择器又是在你点击某按钮时弹出,弹出方式最常见的 ...

  6. 编译Uboot时提示error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory

    在Ubuntu14.04 64位系统中已经安装了libc6:i386的库,编译Uboot时提示error while loading shared libraries: libz.so.1: cann ...

  7. iOS UICollectionView高级用法(长按自由移动cell)-新

    [reference]http://www.jianshu.com/p/31d07bf32d62 iOS 9之后: 示例如下 效果 前言: 看完你可以学到哪些呢? 就是文章标题那么多, 只有那么多. ...

  8. 2781: [JSOI2007]文本生成器

    2781: [JSOI2007]文本生成器 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 8  Solved: 4[Submit][Status][We ...

  9. JAVA文件的两种读取方法和三种写入方法

    在使用java对文件进行读写操作时,有多种方法可以使用,但不同的方法有不同的性能. 此文对常用的读写方法进行了整理,以备不时之需. 1.文件的读取 主要介绍两种常用的读取方法.按行读取和按字符块读取. ...

  10. HNU 13074 Goldbach’s Conjecture 解题报告

    题目大意:输入一个偶数(x<32000),输出这个偶数是由哪两个素数相加所得. 比如:一个偶数26,它可以是3+23,7+19,13+13,这些素数相加所得. 输入输出样例: Sample In ...