ArrayList类的实现

Code:
  1. importjava.util.Iterator;
  2. importjava.util.NoSuchElementException;
  3. publicclassMyArrayList<AnyType>implementsIterable<AnyType>{
  4. privatestaticfinalintDEFAUTL_CAPACITY=10;
  5. privateinttheSize;
  6. privateAnyType[]theItems;
  7. publicMyArrayList(){
  8. clear();
  9. }
  10. publicvoidclear(){
  11. theSize=0;
  12. ensureCapacity(DEFAUTL_CAPACITY);
  13. }
  14. publicintsize(){
  15. returntheSize;
  16. }
  17. publicbooleanisEmpty(){
  18. returnsize()==0;
  19. }
  20. publicvoidtrimToSize(){
  21. ensureCapacity(size());
  22. }
  23. publicAnyTypeget(intidx){
  24. if(idx<0||idx>=size())
  25. thrownewArrayIndexOutOfBoundsException();
  26. returntheItems[idx];
  27. }
  28. publicAnyTypeset(intidx,AnyTypenewVal){
  29. if(idx<0||idx>size())
  30. thrownewArrayIndexOutOfBoundsException();
  31. AnyTypeold=theItems[idx];
  32. theItems[idx]=newVal;
  33. returnold;
  34. }
  35. publicvoidensureCapacity(intnewCapacity){
  36. if(newCapacity<theSize)
  37. return;
  38. //为数组分配内存,并将旧内容拷贝到新数组中
  39. AnyType[]old=theItems;
  40. //因为创建泛型数组是非法的,所以创建一个泛型类型界限的数组,然后使用一个数组进行类型转换
  41. //这将产生一个编译器警告,但在泛型集合的实现中这是不可避免的
  42. //可用注解@SuppressWarnings("unchecked")解除警告
  43. theItems=(AnyType[])newObject[newCapacity];
  44. for(inti=0;i<size();i++)
  45. theItems[i]=old[i];
  46. }
  47. //添加到表的末端病通过调用添加到指定位置的较一般的版本而得以简单的实现
  48. publicbooleanadd(AnyTypex){
  49. add(size(),x);
  50. returntrue;
  51. }
  52. /*
  53. *计算上来说是昂贵的,因为它需要移动在指定位置上或指定位置后面的那些元素到一个更高的位置上
  54. */
  55. publicvoidadd(intidx,AnyTypex){
  56. //add方法可能要求增加容量,扩充容量的代价也是很大的
  57. if(theItems.length==size())
  58. ensureCapacity(size()*2+1);
  59. for(inti=theSize;i>idx;i--)
  60. theItems[i]=theItems[i-1];
  61. theItems[idx]=x;
  62. theSize++;
  63. }
  64. //remove方法类似于add,只是由高位置向低位置移动
  65. publicAnyTyperemove(intidx){
  66. AnyTyperemovedItem=theItems[idx];
  67. for(inti=idx;i<size()-1;i++)
  68. theItems[i]=theItems[i+1];
  69. theSize--;
  70. returnremovedItem;
  71. }
  72. @Override
  73. publicIterator<AnyType>iterator(){
  74. returnnewArrayListIterator();
  75. }
  76. privateclassArrayListIteratorimplementsIterator<AnyType>{
  77. privateintcurrent=0;
  78. @Override
  79. publicbooleanhasNext(){
  80. returncurrent<size();
  81. }
  82. @Override
  83. publicAnyTypenext(){
  84. if(!hasNext())
  85. thrownewNoSuchElementException();
  86. returntheItems[current++];
  87. }
  88. @Override
  89. publicvoidremove(){
  90. MyArrayList.this.remove(--current);
  91. }
  92. }
  93. }

你可能感兴趣的:(ArrayList)