使用泛型自己实现了ArrayList,功能都差不多,只是构造函数初始化的时候有差别。
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);
}
}