设计模式之Iterator(三)

来源:互联网 发布:创建一个数据库sql语句 编辑:程序博客网 时间:2024/05/18 01:26

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

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");}}


0 0
原创粉丝点击