手写实现List接口的ArrayList类
Posted fangtingfei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写实现List接口的ArrayList类相关的知识,希望对你有一定的参考价值。
接口 MyLlist.java
1 package cn.ftf.myarraylist; 2 3 public interface MyList 4 public void clear(); 5 public boolean isEmpty(); 6 public int length(); 7 public Object get(int i) throws Exception; 8 public void add(Object obj); 9 public void inset(int i,Object obj) throws Exception; 10 public void remove(int i) throws Exception; 11 public int indexOf(Object obj); 12 public void display(); 13
集合类 MyArrayList.java
1 package cn.ftf.myarraylist; 2 3 public class MyArrayList implements MyList 4 private Object[] obj; 5 private int a=3; 6 private int curLen=0; 7 8 9 public MyArrayList() 10 super(); 11 obj=new Object[a]; 12 13 14 @Override 15 public void clear() 16 curLen=0; 17 18 19 @Override 20 public boolean isEmpty() 21 return curLen==0; 22 23 24 @Override 25 public int length() 26 return curLen; 27 28 29 @Override 30 public Object get(int i) throws Exception 31 if(i<0||i>curLen-1) 32 throw new Exception("第"+i+"个元素不存在!"); 33 34 return obj[i]; 35 36 37 @Override 38 public void add(Object obj) 39 if(curLen==a) 40 a=a*2; 41 Object [] b=this.obj; 42 this.obj=new Object[a]; 43 for(int i=0;i<=curLen-1;i++) 44 this.obj[i]=b[i]; 45 46 47 this.obj[curLen]=obj; 48 curLen++; 49 50 @Override 51 public void inset(int i, Object obj) throws Exception 52 if(i<0||i>curLen) 53 throw new Exception("插入位置非法!"); 54 55 if(curLen==a) 56 a=a*2; 57 Object [] b=this.obj; 58 this.obj=new Object[a]; 59 for(int i1=0;i1<=curLen-1;i1++) 60 this.obj[i1]=b[i1]; 61 62 63 for(int ii=curLen-1;ii>=i;ii--) 64 this.obj[ii+1]=this.obj[ii]; 65 66 this.obj[i]=obj; 67 curLen++; 68 69 70 @Override 71 public void remove(int i) throws Exception 72 if(i<0||i>curLen) 73 throw new Exception("移除位置非法!"); 74 75 for(int ii=i+1;ii<=curLen;ii++) 76 obj[ii]=obj[ii-1]; 77 78 curLen--; 79 80 81 @Override 82 public int indexOf(Object obj) 83 for(int i=0;i<=curLen;i++) 84 if(this.obj[i].equals(obj)) 85 return i; 86 87 88 return -1; 89 90 91 @Override 92 public void display() 93 for(int i=1;i<=curLen;i++) 94 System.out.println(obj[i-1]+" "); 95 96 97 98 99
测试类 Test01.java
1 package cn.ftf.myarraylist; 2 3 public class Test01 4 public static void main(String[] args) throws Exception 5 MyArrayList ma=new MyArrayList(); 6 MyList ml=new MyArrayList(); 7 ml.add(1); 8 ml.add("hello"); 9 ml.add(2); 10 ml.add("word"); 11 ml.display(); 12 13 System.out.println(ml.get(3)); 14 ml.inset(3, "插入的"); 15 ml.inset(3, "插入的2"); 16 ml.display(); 17 System.out.println(ml.length()); 18 System.out.println(ml.isEmpty()); 19 ml.clear(); 20 System.out.println(ml.isEmpty()); 21 22 23 24 25
/*
运行结果:(无差错)
1
hello
2
word
word
1
hello
2
插入的2
插入的
word
6
false
true
*/
以上是关于手写实现List接口的ArrayList类的主要内容,如果未能解决你的问题,请参考以下文章
JavaSE基础八----<集合>List接口及其实现类,List接口的迭代