内功心法 -- java.util.ArrayList<E> (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
内功心法 -- java.util.ArrayList<E> (5)的更多相关文章
- 内功心法 -- java.util.ArrayList<E> (1)
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...
- 内功心法 -- java.util.ArrayList<E> (2)
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...
- 内功心法 -- java.util.ArrayList<E> (3)
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...
- 内功心法 -- java.util.ArrayList<E> (4)
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...
- 内功心法 -- java.util.ArrayList<E> (6)
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...
- 解决springmvc报No converter found for return value of type: class java.util.ArrayList问题
一.背景 最近闲来无事,想自己搭建一套Spring+SpringMVC+Mybatis+Mysql的环境(搭建步骤会在以后博客中给出),结果运行程序时,适用@ResponseBody注解进行返回Lis ...
- Java.util.ArrayList详解
java.util.ArrayList就是传说中的动态数组. 继承了关系,有此可看出ArrayList与list的collection的关系 public class ArrayList<E&g ...
- java@ 利用ArrayList实现dijkstra算法以及topological 排序算法(java.util.ArrayList)
package dataStructure; import java.util.ArrayList; import java.util.LinkedList; import java.util.Que ...
- java.util.ArrayList、java.util.vector和java.util.LinkedList (JDK 1.8.0_111)
一.java.util.ArrayList 1.1 ArrayList 继承结构 ArrayList实现了RandomAccess,可以随机访问(其实就是通过数组下标访问):实现了Cloneable, ...
随机推荐
- 串口通信中ReadFile和WriteFile的超时详解!
源:串口通信中ReadFile和WriteFile的超时详解! 在用ReadFile和WriteFile读写串行口时,需要考虑超时问题.如果在指定的时间内没有读出或写入指定数量的字符,那么ReadFi ...
- Linux中cat、more、less、tail、head命令的区别
一.cat 显示文件连接文件内容的工具 cat 是一个文本文件(查看)和(连接)工具,通常与more搭配使用,与more不同的是cat可以合并文件.查看一个文件的内容,用cat比较简单,就是cat后面 ...
- HTML中meta的应用
meta是用来在HTML文档中模拟HTTP协议的响应头报文.meta 标签用 于网页的<head>与</head>中,meta 标签的用处很多.meta 的属性有两种:name ...
- iOS给model排序
今天有朋友问我怎么给Model排序,我顺便写了一个例子, 以下是代码,很简洁可以直接用. Person *per = [[Person alloc] init]; per.name = @" ...
- 理解javascript函数的重载
javascript其实是不支持重载的,这篇文章会和java语言函数的重载对比来加深对javascript函数重载的理解. 以下我会假设读者不了解什么是重载所以会有一些很基础的概念 ...
- jQuery简单实现图片预加载
我们在做网站的时候经常会遇到这样的问题:一个页面有大量的图片导致页面加载速度缓慢,经常会出现一个白页用户体验很不好.那么如何解决这个问题呢?下面我来介绍一种在实际应用中经常会使用到的js预加载的方法. ...
- STM32_IAP详解(有代码,有上位机)
Iap,全名为in applacation programming,即在应用编程,与之相对应的叫做isp,in system programming,在系统编程,两者的不同是isp需要依靠烧写器在单片 ...
- ios UIKit动力 分类: ios技术 2015-07-14 12:55 196人阅读 评论(0) 收藏
UIkit动力学是UIkit框架中模拟真实世界的一些特性. UIDynamicAnimator 主要有UIDynamicAnimator类,通过这个类中的不同行为来实现一些动态特性. 它一般有两种初始 ...
- STL中list用法
本文以List容器为例子,介绍了STL的基本内容,从容器到迭代器,再到普通函数,而且例子丰富,通俗易懂.不失为STL的入门文章,新手不容错过! 0 前言 1 定义一个list 2 使用list的成员函 ...
- iOS 获取本地文件的各种坑
1.无论:TXT,EPUB,PDF等各种格式的文件,保存到本地的时候,最好都保存成字母或者数字,不要保存成汉字,否则,在取文件的时候,由于编码的问题,各种瓦特 2.如果文件名真的保存成了汉字,那么进行 ...