自己实现ArrayList
2015-03-10 17:26
127 查看
使用泛型自己实现了ArrayList,功能都差不多,只是构造函数初始化的时候有差别。
ArrayList源代码内部是使用Object[]来保存你add的对象的,然后在你get的时候再强制转换一下。本文是直接申请的模板类型的数组T[]。因此在调用构造函数时需要将类的类型也传入,详见代码。
ArrayList源代码内部是使用Object[]来保存你add的对象的,然后在你get的时候再强制转换一下。本文是直接申请的模板类型的数组T[]。因此在调用构造函数时需要将类的类型也传入,详见代码。
</pre><pre name="code" class="java">package tools; import java.lang.reflect.Array; import java.util.Iterator; public class MyArrayList<T> implements Iterable<T> { private int size; private int cap; private T[] array; private Class<T> type; public MyArrayList(Class<T> type, int cap){ this.type = type; this.size = 0; this.cap = cap; } public MyArrayList(Class<T> type){ this.type = type; this.size = 0; this.cap = 128; this.array = (T[]) Array.newInstance(type, this.cap); } private void lager(){ T[] temp = (T[]) Array.newInstance(this.type, this.cap*2); for(int i = 0; i < this.cap; ++i){ temp[i] = this.array[i]; } this.array = temp; this.cap = this.cap * 2; } public void add(T obj){ if(size==cap){ lager(); } this.array[size++]=obj; } public T get(int index){ if(index < this.size){ return this.array[index]; } return null; } public T remove(int index){ if(index < this.size){ T temp = this.array[index]; for(int i = index; i < this.size-1; ++ i){ this.array[i] = this.array[i+1]; } this.size-=1; return temp; } return null; } public int getSize(){ return this.size; } @Override public Iterator<T> iterator() { // TODO Auto-generated method stub return new ALIterator(); } class ALIterator implements Iterator<T>{ private int _index; @Override public boolean hasNext() { // TODO Auto-generated method stub return _index != size; } @Override public T next() { // TODO Auto-generated method stub return array[_index ++]; } } }测试代码:
package tools; import java.util.ArrayList; import java.util.List; public class ArrayListTest { public static void main(String[] args) { // TODO Auto-generated method stub MyArrayList<A> array = new MyArrayList<A>(A.class, 2); array.add(new A(1)); System.out.println(array.getSize()); array.add(new A(2)); array.add(new A(3)); System.out.println(array.getSize()); for(A i : array){ i.print(); } } } class A{ private int id; public A(int id){ this.id = id; } public void print(){ System.out.println("A.class " + this.id); } }
相关文章推荐
- 数据结构—顺序表(自己实现Java的ArrayList)
- 小伙伴来自己实现一个ArrayList
- Java之实现自己的ArrayList与LinkedList
- 《小白兔到大黑牛》第二篇基于源码自己实现简单的ArrayList中简单方法
- JAVA--自己实现ArrayList
- 自己理解的java.util.ArrayList(二)实现类
- 自己用java实现LinkList和arrayList
- 自己实现一下ArrayList
- 自己动手系列——实现一个简单的ArrayList
- 自己动手实现集合框架类(一)之ArrayList
- 实现自己的ArrayList和HashMap
- Java中SJBArrayList自己简单实现ArrayList
- 自己动手实现ArrayList
- ArrayList 自己实现。
- 自己实现一个ArrayList,模仿ArrayList类的底层结构
- 自己写的一个ArrayLIST,but 不知道怎么很好的实现System底下的arraycopy方法
- 容器第三课,JDK源码分析,自己实现ArrayList数组扩容
- MyArrayList——自己实现ArrayList
- Java -- 自己实现数组列表(Arraylist)
- 101-102_容器_JDK源代码分析_自己实现ArrayList