仿照ArrayList自己生成的MyList对象

现在需要自己生成一个list集合,基本雷同ArrayList,不使用API的List接口。

实现如下:

  MyList的代码:

    

 1 public class MyList<T> {
 2  
 3     private T [] t;
 4     
 5     
 6     public MyList () {
 7         Object obj[]=new Object[1];
 8         t=(T[]) obj;    
 9     }
10     /**
11      * 添加集合对象
12      * @param info
13      */
14     public void add(T info){
15         if(t[0]==null){
16             t[0]=info;
17         }else{
18             addLength(t);
19             t[t.length-1]=info;
20         }
21         
22     }
23     /**
24      * 返回集合长度
25      * @return int
26      * 2017年4月13日
27      */
28     public int size(){
29         return this.t.length;
30     }
31    
32     
33     /**
34      * 获取下标对应的对象
35      * @param i
36      * @return T
37      */
38     public T getOfIndex(int i){
39     
40         return t[i];
41     }  
42     
43     /**
44      * 增长集合长度
45      * @param t
46      */
47     private void  addLength(T[] t){
48         Object [] ts1=new Object[t.length+1];
49         for(int i=0;i<t.length;i++){
50             ts1[i]=t[i];
51         }
52         this.t=(T[]) ts1;
53     }
54 }

测试类

 1 public class TestMyList {
 2 
 3     public static void main(String[] args) {
 4         MyList<String> list=new MyList<String>();
 5         
 6         list.add("a");
 7         list.add("b");
 8         
 9         for(int i=0;i<list.size();i++){
10             System.out.println(list.getOfIndex(i));
11         }
12     }
13 }

输出结果:

a
b

这样一个简单的集合就完成了,现在只支持添加对象。

原文地址:https://www.cnblogs.com/wangzun/p/6704112.html