java ArrayList实现

public class MyArrayList<AnyType extends Comparable<? super AnyType>> implements Iterable<AnyType>{
	
	//默认新建数组大小
	private static final int DEFAULT_CAPACITY = 10;
	
	//表中元素个数
	private int theSize;
	private AnyType[] theItems;
	
	//数组初始化
	private void doClear() {
		theSize = 0;
		ensureCapacity(DEFAULT_CAPACITY);
	}
	
	//设置一个容量更大的数组并将原数组内容复制
	private void ensureCapacity(int newCapacity) {
		if(newCapacity < theSize)
			return;
		else {
			AnyType[] old = theItems;
			theItems = (AnyType[]) new Object[newCapacity];
			for(int i = 0; i < theSize; i++) {
				theItems[i] = old[i];
			}
		}
	}
	
	//
	public void clear() {
		doClear();
	}
	
	//返回表中元素个数
	public int size() {
		return theSize;
	}
	
	public boolean isEmpty() {
		return theSize == 0;
	}
	
	public AnyType get(int i) {
		if(i < 0 || i >= theSize) {
			throw new ArrayIndexOutOfBoundsException();
		}
		else {
			return theItems[i];
		}
	}
	
	public AnyType set(int i, AnyType newVal) {
		if(i < 0 || i >= theSize) {
			throw new ArrayIndexOutOfBoundsException();
		}
		else {
			AnyType oldVal = theItems[i];
			theItems[i] = newVal;
			return oldVal;
		}
	}
	
	public void add() {
		if(theSize + 1 < theItems.length) {
			ensureCapacity(theSize * 2);
		}
	}
	
	//默认无参构造
	public MyArrayList() {
		doClear();
	}

	@Override
	public java.util.Iterator<AnyType> iterator(){
		return new ArrayIterator();
	}
	
	//内部类迭代器
	private class ArrayIterator implements java.util.Iterator<AnyType>{
		
		private int index = 0;
		
		@Override
		public boolean hasNext() {
			if(index + 1 < theSize) {
				return true;
			}
			else{
				return false;
			}
		}

		@Override
		public AnyType next() {
			if(hasNext()) {
				return theItems[index++];
			}
			else {
				return null;
			}
		}
		
	}
}

内部类实现迭代器

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值