List的的另一种实现方法的尝试

来源:互联网 发布:淘宝vr眼镜宣传视频 编辑:程序博客网 时间:2024/05/29 16:51

jdk里的ArrayList是用Object数组不断扩充长度实现的,这里尝试用内部类递归来实现下,没事写着玩,大神别见怪!!

package javas.lang.reflect.create;public class List<T> {    private InnerList innerlist ;    public List(){        innerlist=new InnerList();    }    private  static  int index=-1;    public int size(){        return index+1 ;    }    public void add(T t){        innerlist.cycleadd(t,++index);    }    public T get(int i) throws Exception{        if (i>index) {            throw new Exception("没有这个元素!");        }        return innerlist.get(i);    }    public static void main(String[] args) throws Exception {        List<String> list=new List<String>();        list.add("美女1 ");        list.add("美女2 ");        list.add("美女3 ");        list.add("美女4 ");        list.add("美女5 ");        System.out.println(list.size());        System.out.println(list.get(3));    }    class InnerList{        int i=0;        private T t;        private InnerList innerlist=null;        public InnerList(){        }        public T get(int i2) {            if (i2==i) {                return t;            }else{                return innerlist.get(i2);            }        }        public void cycleadd(T t2,int index) {            // TODO Auto-generated method stub            if (i==0) {                this.t=t2;                i=index;            }else{                if (innerlist==null)                innerlist=new InnerList();                innerlist.cycleadd(t2, index);            }           }    }}

输出结果:

5
美女5

原创粉丝点击