- importjava.util.Iterator;
- importjava.util.NoSuchElementException;
- publicclassMyArrayList<AnyType>implementsIterable<AnyType>{
- privatestaticfinalintDEFAUTL_CAPACITY=10;
- privateinttheSize;
- privateAnyType[]theItems;
- publicMyArrayList(){
- clear();
- }
- publicvoidclear(){
- theSize=0;
- ensureCapacity(DEFAUTL_CAPACITY);
- }
- publicintsize(){
- returntheSize;
- }
- publicbooleanisEmpty(){
- returnsize()==0;
- }
- publicvoidtrimToSize(){
- ensureCapacity(size());
- }
- publicAnyTypeget(intidx){
- if(idx<0||idx>=size())
- thrownewArrayIndexOutOfBoundsException();
- returntheItems[idx];
- }
- publicAnyTypeset(intidx,AnyTypenewVal){
- if(idx<0||idx>size())
- thrownewArrayIndexOutOfBoundsException();
- AnyTypeold=theItems[idx];
- theItems[idx]=newVal;
- returnold;
- }
- publicvoidensureCapacity(intnewCapacity){
- if(newCapacity<theSize)
- return;
- //为数组分配内存,并将旧内容拷贝到新数组中
- AnyType[]old=theItems;
- //因为创建泛型数组是非法的,所以创建一个泛型类型界限的数组,然后使用一个数组进行类型转换
- //这将产生一个编译器警告,但在泛型集合的实现中这是不可避免的
- //可用注解@SuppressWarnings("unchecked")解除警告
- theItems=(AnyType[])newObject[newCapacity];
- for(inti=0;i<size();i++)
- theItems[i]=old[i];
- }
- //添加到表的末端病通过调用添加到指定位置的较一般的版本而得以简单的实现
- publicbooleanadd(AnyTypex){
- add(size(),x);
- returntrue;
- }
- /*
- *计算上来说是昂贵的,因为它需要移动在指定位置上或指定位置后面的那些元素到一个更高的位置上
- */
- publicvoidadd(intidx,AnyTypex){
- //add方法可能要求增加容量,扩充容量的代价也是很大的
- if(theItems.length==size())
- ensureCapacity(size()*2+1);
- for(inti=theSize;i>idx;i--)
- theItems[i]=theItems[i-1];
- theItems[idx]=x;
- theSize++;
- }
- //remove方法类似于add,只是由高位置向低位置移动
- publicAnyTyperemove(intidx){
- AnyTyperemovedItem=theItems[idx];
- for(inti=idx;i<size()-1;i++)
- theItems[i]=theItems[i+1];
- theSize--;
- returnremovedItem;
- }
- @Override
- publicIterator<AnyType>iterator(){
- returnnewArrayListIterator();
- }
- privateclassArrayListIteratorimplementsIterator<AnyType>{
- privateintcurrent=0;
- @Override
- publicbooleanhasNext(){
- returncurrent<size();
- }
- @Override
- publicAnyTypenext(){
- if(!hasNext())
- thrownewNoSuchElementException();
- returntheItems[current++];
- }
- @Override
- publicvoidremove(){
- MyArrayList.this.remove(--current);
- }
- }
- }