设计模式之Iterator(三)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010995220/article/details/51265246

容器中泛型的使用,取出更方便(不用转型)

package com.awiatech.iterator.generic;

public class GenericArrayList<E> {
	Object[] objects = new Object[10]; // 定义一个长度为10的数组
	int index = 0; // 数组索引指向
	
	/**
	 * 数组中添加元素
	 * @param o 要添加的元素
	 */
	public void add(E o){
		// 当原数组数据满时再开辟两倍长度的新数组,并拷贝原数组数据至新数组中,并将原数组指向新数组
		if(index == objects.length){
			Object[] newObjects = new Object[objects.length * 2];
			System.arraycopy(objects, 0, newObjects, 0, objects.length);
			objects = newObjects;
		}
		objects[index] = o; // 元素添加到数组
		index ++; // 移动索引指向
	}
	
	/**
	 * 数组中元素的个数
	 * @return 返回数组中元素的个数
	 */
	public int size(){
		return index;
	}
	
	public static void main(String[] args) {
		GenericArrayList<String> a = new GenericArrayList<String>();
		a.add("hello");

	}

}


猜你喜欢

转载自blog.csdn.net/u010995220/article/details/51265246