自己手写一个Java的ArrayList

围巾🧣 2020年03月21日 632次浏览

思想

  • 基本要求:需要使用泛型,很多类可以形成列表。可迭代的
  • 成员变量:默认容量,数量,一个泛型数组
  • 成员方法:构造方法、clear、size、isEmpty、get、set、add、remove、ensureCapacity

代码

  1. class MyArrayList<AnyType> implements Iterable<AnyType> {

  2. private static final int DEFAULT_CAPACITY = 10;
  3. private int theSize;
  4. private AnyType[] theItems;

  5. public MyArrayList() {
  6. doClear();
  7. }

  8. private void clear() {
  9. doClear();
  10. }

  11. private void doClear() {
  12. theSize = 0;
  13. ensureCapacity(DEFAULT_CAPACITY);
  14. }

  15. public int size() {
  16. return theSize;
  17. }

  18. public boolean isEmpty() {
  19. return size() == 0;
  20. }

  21. public void trimToSize() {
  22. ensureCapacity(size());
  23. }

  24. public AnyType get(int idx) {
  25. if (idx < 0 || idx >= size()) {
  26. throw new ArrayIndexOutOfBoundsException();
  27. }
  28. return theItems[idx];
  29. }

  30. public AnyType set(int idx, AnyType newVal) {
  31. if (idx < 0 || idx >= size()) {
  32. throw new ArrayIndexOutOfBoundsException();
  33. }
  34. AnyType old = theItems[idx];
  35. theItems[idx] = newVal;
  36. return old;
  37. }

  38. public void ensureCapacity(int newCapacity) {
  39. if (newCapacity < theSize) {
  40. return;
  41. }

  42. AnyType[] old = theItems;
  43. theItems = (AnyType[]) new Object[newCapacity];
  44. for (int i = 0; i < size(); i++) {
  45. theItems[i] = old[i];
  46. }
  47. }

  48. public void add(int idx, AnyType x) {
  49. if (theItems.length == size()) {
  50. ensureCapacity(size() * 2 + 1);
  51. }
  52. for (int i = theSize; i > idx; i--) {
  53. theItems[i] = theItems[i - 1];
  54. }
  55. theItems[idx] = x;
  56. theSize++;
  57. }

  58. public void add(AnyType x) {
  59. if (theItems.length == size()) {
  60. ensureCapacity(size() * 2 + 1);
  61. }

  62. theItems[theSize] = x;
  63. theSize++;
  64. }

  65. public AnyType remove(int idx) {
  66. AnyType removedItem = theItems[idx];
  67. for (int i = idx; i < size() - 1; i++) {
  68. theItems[i] = theItems[i + 1];
  69. }
  70. theSize--;
  71. return removedItem;
  72. }


  73. @Override

  74. public Iterator<AnyType> iterator() {
  75. return new ArrayListIterator();
  76. }

  77. // 加一个迭代器内部类,表的iterator()要返回一个迭代器
  78. class ArrayListIterator implements java.util.Iterator<AnyType> {

  79. private int current = 0;

  80. //下面实现迭代器基本的三个方法
  81. @Override
  82. public boolean hasNext() {
  83. return current < size();
  84. }

  85. @Override
  86. public AnyType next() {
  87. if (!hasNext()) {
  88. throw new java.util.NoSuchElementException();
  89. }
  90. return theItems[current++];
  91. }

  92. @Override
  93. public void remove() {
  94. MyArrayList.this.remove(--current);
  95. }

  96. }

  97. }