数据结构之顺序表

package cn.thj.data_structures;

import java.util.Iterator;

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

	// 定义默认的大小
	private static final int DEFAULT_CAPACITY = 10;
	private T[] Items;
	private int size;

	// 默认构造
	public MyArrayList() {
		clear();
	};

	// 清空集合
	public void clear() {
		size = 0;
		ensureCapacity(DEFAULT_CAPACITY);
	}

	/**
	 * 保持集合容量增长
	 * 
	 * @param newCapacity
	 */
	public void ensureCapacity(int newCapacity) {
		if (newCapacity < size) {
			return;
		}
		T[] old = Items;
		Items = (T[]) new Object[newCapacity];
		for (int i = 0; i < size(); i++) {
			Items[i] = old[i];
		}
	}

	// 返回集合的大小
	public int size() {
		return size;
	}

	// 是集合的容量为集合的大小
	public void trimToSize() {
		ensureCapacity(size());
	}

	// 判断集合是否为空
	public boolean isEmpty() {
		return size() == 0;
	}

	// 检查集合的边界,判断是否越界
	private void RangeCheck(int index) {
		if (index >size || index < 0)
			throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
					+ size);
	}

	// 取指定位置的值
	public T get(int index) {
		RangeCheck(index);
		return Items[index];
	}

	// 给指定位置设值
	public T set(int index, T newVal) {
		RangeCheck(index);
		T old = Items[index];
		Items[index] = newVal;
		return Items[index];
	}
	// 添加元素,默认添加到末尾
	public boolean add(T val) {
		add(size(), val);
		return true;
	}

	/**
	 * 根据指定位置添加数据
	 * 
	 * @param index
	 *            添加的位置
	 * @param val
	 *            添加的值
	 */
	public void add(int index, T val) {
		RangeCheck(index);
		if (Items.length == size()) {
			ensureCapacity(size() * 2 + 1);
		}
		for (int i = size; i > index; i--) {
			Items[i] = Items[i - 1];
		}
		Items[index] = val;
		size++;
	}

	/**
	 * 删除指定位置的元素
	 * 
	 * @param index
	 * 删除的位置
	 * @return removeItem 
	 * 返回被删除的元素
	 */
	public T remove(int index) {
		RangeCheck(index);
		T removeItem = Items[index];
		for (int i = index; i < size; i++) {
			Items[i] = Items[i + 1];
		}
		size--;
		return removeItem;
	}
    
	public Iterator<T> iterator() {
		return new ArrayListIterator();
	}

	/**
     *实现迭代器,这里是用一个内部类来实现的
	 */
	private class ArrayListIterator implements java.util.Iterator<T> {
		private int current = 0;
		private boolean okToRemove = false;

		public boolean hasNext() {
			return current < size();
		}

		public T next() {
			if (!hasNext())
				throw new java.util.NoSuchElementException();

			okToRemove = true;
			return Items[current++];
		}

		public void remove() {
			if (!okToRemove)
				throw new IllegalStateException();

			MyArrayList.this.remove(--current);
			okToRemove = false;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值