仿照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

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


__EOF__

本文作者Jun10ng
本文链接https://www.cnblogs.com/wangzun/p/6704112.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   Johnson_wang  阅读(322)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示