数据结构与算法的Java实现——ArrayList

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyArrayList<T> implements Iterable<T> {

	public static final int INITIAL_CAPACITY = 10;
	
	private int theSize;
	private T[] items;
	
	public MyArrayList() {
		clear();//由于构造方法和clear()方法的实现一样,所以此处调用clear方法
	}
	
	public int size() {
		return theSize;
	}
	
	public boolean isEmpty() {
		return size() == 0;//对于返回类型为boolean的方法,有时只需直接将逻辑表达式写在return后面即可
	}
	
	/**
	 * 删掉所有元素,容量设为初始大小
	 */
	public void clear() {
		theSize = 0;
		extendCapacity(INITIAL_CAPACITY);
	}
	
	public boolean add(T item) {//追加元素为插入元素的一种特殊情况
		insert(size(), item);
		return true;
	}
	
	public void insert(int index, T item) {
		if(size() == items.length)
			extendCapacity(size() * 2 + 1);
		for(int i = theSize; i > index; i--)
			items[i] = items[i-1];
		items[index] = item;
		theSize++;
	}
	
	public T remove(int index) {
		if(index<0 || index>= size())
			return null;
		T old = items[index];//先将要删除的元素保存下来,以便后续返回
		for (int i = index; i < size()-1; i++) {
			items[i] = items[i+1];
		}
		theSize--;
		return old;
	}
	
	public void extendCapacity(int newCapacity) {
		T[] oldItems = items;//先将原本的元素保存下来,防止下一步新建数组时元素被覆盖
		items = (T[]) new Object[newCapacity];
		for (int i = 0; i < size(); i++) {
			items[i] = oldItems[i];
		}
	}
	
	public T get(int index) {
		if(index<0 || index>= size())
			throw new IndexOutOfBoundsException();
		return items[index];
	}
	
	public T set(int index, T item) {
		if(index<0 || index>= size())
			throw new IndexOutOfBoundsException();
		T old = items[index];//先将被替换的元素保存下来,以便后续返回
		items[index] = item;
		return old;
	}
	
	@Override
	public Iterator<T> iterator() {
		return new MyIterator();
	}

	private class MyIterator implements Iterator<T>{//将迭代器定义为内部类,以便能够使用MyArrayList中的私有变量
		private int current = 0;
		
		@Override
		public boolean hasNext() {
			return current < size();
		}

		@Override
		public T next() {
			if(!hasNext())
				throw new NoSuchElementException();
			return items[current++];
		}
		
		@Override
		public void remove() {
			MyArrayList.this.remove(--current);//由于获取下一个元素时current+1,所以要想删除获取的元素,需要先将current-1
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值