Java源码阅读之ArrayList<E> 下

Java源码阅读之ArrayList 下

Java源码阅读之ArrayList上

方法

// 返回当前list的listIterator,起始索引为index,也即是第一次调用next()方法返回的元素是索引为index的元素
// 第一次调用previous()方法返回的是index减一的元素
public ListIterator<E> listIterator(int index){
	if(index < 0 || index > szie){
		throw new IndexOutOfBoundsException("Index: "+index);
	}		
	return new ListItr(index);
}

// 返回一个默认的ListIterator,默认索引为0
public ListIterator<E> listIterator(){
	return new ListItr(0);
}

// 返回一个默认的Iterator,没有ListIterator的previous方法
public Iterator<E> iterator(){
	return new Itr();
} 

// 内部类实现迭代器
private class Itr implements Iterator<E>{
	// 下一个next方法返回的元素的索引
	int cursor;
	// 上一个返回的元素的索引,如果没有就是-1
	int lastRet = -1;
	// 乐观锁,用于在遍历期间识别List是否已经改变过
	int expectedModCount = modCount;

	Itr(){
		// 默认构造器,cursor会被初始化为0,也即是默认情况下的迭代器
	}

	// 判断当前是否已经遍历到list的末尾
	public boolean hasNext(){
		return cursor != size;
	}
	
	// 返回下一个元素
	public E next(){
		// 检查乐观锁,查看list是否已经发生改变
		checkForModification();
		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];
	}

	// 删除上一个返回的元素,必须先调用一次next方法之后才能调用该方法
	public void remove(){
		if(lastRet < 0){
			throw new IllegalStateException();
		}
		checkForModification();
		try{
			ArrayList.this.remove(lastRet);
			cursor = lastRet;
			// 不能连续调用两次remove方法
			lastRet = -1;
			expectedModCount = modCount;
		}catch(IndexOutOfBoundsException e){
			throw new ConcurrentModificationException();
		}
	}
	
	// Consumer是函数式接口,消耗一个变量
	// 这里使用? super E ,确保传递进来的是E即E的父类
	public void foreachRemaining(Consumer<? super E> consumer){
		Objects.requireNonNull(consumer);
		final int size = ArrayList.this.size;
		// 如果在调用该方法之前调用了next方法,则该方法是接在next方法之后的元素进行遍历
		int i = cursor;
		if(i >= cursor)
			// 已经遍历到list的尾部
			return;
		final Object[] elementData = ArrayList.this.elementData;
		if(i >= elementData.length)
			throw new ConcurrentModificationException();
		while(i != size && exceptedModeCount == modCount)
			consumer.accept((E) elementData[i++]);
		cursor = i;
        lastRet = i - 1;
        checkForComodification();
	}
	
	final void checkForComodification(){
		if(exceptedModCount != modCount)
			throw new ConcurrentModificationException();
	}
}

private class ListItr extends Itr implements ListIterator<E>{
	//如果在外面没有指定index,则会默认指定为0
	ListItr(int index){
		super();
		cursor = index;
	}
	public boolean hasPrevious(){
		return cursor != 0;
	}
	public int nextIndex(){
		return cursor;
	}
	public int previousIndex(){
		return cursor - 1;
	}

	public E previous(){
		checkForComodification();
		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[i];
	}
	// 修改上一次返回的元素的值
	public void set(E e){
		if(lastRet < 0)
			throw new IllegalStateException();
		checkForComodification();
		try{
			ArrayList.this.set(lastRet, e);
		}catch(IndexOutOfBoundsException e){
			throw new ConcurrentModificationException();
		}
		
	}
	
	// 让插入的元素e的索引为当前索引,且next指向下一个元素
	public void add(E e){
		try{
			int i = cursor;
			ArrayList.this.add(i, e);
			cursor = i + 1;
			lastRet = -1;
			expectedModCount = modCount;
		}catch(IndexOutOfBoundsException e){
			throw new ConcurrentModificationException();
		}
	}

	public void forEach(Consumer<? super E> consumer){
		Objects.requireNonNull(consumer);
		final int expectedModCount = modCount;
		final E[] elementData = (E[]) this.elementData;
		final int size = this.size;
		for(int i = 0; expectedModCount == modCount && i < size; i++)
			consumer.accpet(elementData[i]);
		if(expectedModCount != modCount)
			throw new ConcurrentModificationException();
	}

	public Spliterator<E> spliterator(){
		return new ArrayListSpliterator<>(this, 0, -1, 0);
	}
}
	// 一个惰性加载的可分割迭代器,只有在需要使用的时候才进行初始化
	// 迭代器在调用tryAdvance和forEachRemaining之前均可以进行修改
	static final class ArrayListSpliterator<E> implements Spliterator<E>{
		private final ArrayList<E> list;
		private int index;
		private int fence;
		private int expectedModCount;

		ArrayListSpliterator(ArrayList<E> list, int origin, int fence, int expectedModCount){
			this.list = list;
			this.index = origin;
			this.fence = fence;
			this.expectedModCount = expectedModCount;
		}
		private int genFence(){
			int hi;
			ArrayList<E> lst;
			// 表示迭代器是第一次使用对fence进行初始化
			if((hi = fence) < 0){
				if((lst = list) == null)
					// 如果list为null则将fence初始化为0
					hi = fence = 0;
				else
					this.expectedModCount = lst.modCount;
					hi = fence = lst.size;
			}
			return hi;
		}
		
		private ArrayListSpliterator<E> trySplit(){
			int hi = getFence(), lo = index, mid = (hi + lo) >>> 1;
			// 返回的迭代器处理前半部分
			return (lo >= mid) ? null : new ArrayListSpliterator<E>(list, lo , index = mid, expectedModCount);
		}
		public boolean tryAdvance(Consumer<? super E> consumer){
			if(consumer == null)
				throw new NullPointerException();
			int hi = getFence(), i = index;
			if(i < hi){
				index = i + 1;
				E e = (E)list.elementData[i];
				consumer.accpet(e);
				if(list.modCount != expectModCount)
					throw new ConcurrentModificationException();
				return true;
			}
			return false;
		}
		public void forEachRemaining(Comsumer<? super E> action){
			int i, hi, mc;
			ArrayList<E> lst, Object[] a;
			if(action == null)
				throw new NullPointerException();
			if((lst = list) != null && (a = list.elementData) != null){
				if((hi = fence) < 0){
					// 如果是第一次使用,则对迭代器进行初始化
					hi = list.size;
					mc = list.modCount;
				}else{
					// 不是第一次使用
					mc = exceptedModCount;
				}
				if((i = index) >= 0 && (index = hi) <= a.length){
					for(; i < hi; i++){
						E e = (E) a[i];
						action.accept(e);
					}
					if(lst.modCount == mc)
						return;
				}
			}
			throw new ConcurrentModificationException();
		}
	}

public boolean removeIf(Predicate<? super E> filter){
	Objects.requireNonNull(filter);
}

public void replaceAll(UnaryOperator<E> operator){
	Objects.requireNonNull(operator);
	// 期望的乐观锁数值
	final int expectedModCount = modCount;
	// 当前list的大小
	final int size = this.size;
	for(int i = 0; i < size && modCount == expectedModCount; i++){
		elementData[i] = operator.apply((E) elementData[i]);
	}
	if(modCount != expectedModCount)
		throw new ConcurrentModificationException();
	modCount++;
}

public void sort(Comparator<? extends E> c){
	final int expectedModCount = modCount;
	Arrays.sort((E[]) elementData, 0, size,c);
	if(modCount != expectedModCount){
		throw new ConcurrentModificationException();
	}
	modCount ++;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值