论坛首页 Java企业应用论坛

ArrayList的模拟

浏览 1465 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-06-06  
public class ArrayList<E> {
	
	//定义一个Object类型的数组,长度为10
	private Object[] o = new Object[10];
	
	/**
	 * 增加 指定为E的对象的元素
	 * @param e new 对像所指定的无素类型
	 */
	public void add(E e) {
		/**
		 * 判断数组是否已满
		 * 如查满了,新定义一个数组,长度为原数组的长度+5
		 * 把o 指向新定义的数组
		 */
		if (this.o[this.o.length - 1] != null) {

			Object[] o2 = new Object[this.o.length + 5];
			/*
			 * 拷贝数组
			 * 把o数组里面的元素全部 copy到新数组里面去
			 */
			System.arraycopy(this.o, 0, o2, 0, this.o.length);
			this.o = o2;
		}
		/**
		 * 判断o数组哪个无素为空,就将其下标指下新加进来的对象
		 */
		for (int i = 0; i < this.o.length; i++) {

			if (this.o[i] == null) {
				this.o[i] = e;
				break;
			}

		}
	}
	
	/**
	 * 得到其不为空的元素的个数
	 * @return o数组中不为空的无素的个数
	 */
	public int size(){
		int size =0;
		for(int i =0; i<this.o.length;i++){
			
			if(this.o[i]!=null){
				size++;
			}else{
				break;
			}
		}
		
		return size;
	}
	/**
	 * 得到o数组下标值为index的元素
	 * @param index 下标值
	 * @return o数组下标值为index的元素
	 */
	@SuppressWarnings("unchecked")
	public E get(int index){
		
		return (E)this.o[index];
		
	}

}

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics