|
| 1 | +package com; |
| 2 | + |
| 3 | +import java.util.NoSuchElementException; |
| 4 | + |
| 5 | +public class MyArrayList implements MyList { |
| 6 | + |
| 7 | + private static final int DEFAULT_CAPACITY = 10; |
| 8 | + private int size; |
| 9 | + private Object[] elementData; |
| 10 | + |
| 11 | + public MyArrayList() { |
| 12 | + this.size = 0; |
| 13 | + |
| 14 | + } |
| 15 | + |
| 16 | + @Override |
| 17 | + public boolean add(Object o) { |
| 18 | + // TODO Auto-generated method stub |
| 19 | + add(size(), o); |
| 20 | + return true; |
| 21 | + } |
| 22 | + |
| 23 | + @Override |
| 24 | + public void add(int index, Object o) { |
| 25 | + |
| 26 | + if (elementData.length == size()) { |
| 27 | + ensureCapacity(size() * 2 + 1); |
| 28 | + } |
| 29 | + |
| 30 | + for (int i = size(); i > index; i--) { |
| 31 | + elementData[i] = elementData[i - 1]; |
| 32 | + } |
| 33 | + elementData[2] = o; |
| 34 | + size++; |
| 35 | + |
| 36 | + } |
| 37 | + |
| 38 | + @Override |
| 39 | + public Object get(int index) { |
| 40 | + |
| 41 | + if (index < 0 || index >= size()) { |
| 42 | + throw new ArrayIndexOutOfBoundsException(); |
| 43 | + } |
| 44 | + |
| 45 | + return elementData[index]; |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + @Override |
| 50 | + public Object remove(int index) { |
| 51 | + |
| 52 | + if (index < 0 || index >= size()) { |
| 53 | + throw new ArrayIndexOutOfBoundsException(); |
| 54 | + } |
| 55 | + Object value = elementData[index]; |
| 56 | + for (int i = index; i < size() - 1; i++) { |
| 57 | + elementData[i] = elementData[i + 1]; |
| 58 | + } |
| 59 | + return value; |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public int size() { |
| 65 | + // TODO Auto-generated method stub |
| 66 | + return size; |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * 检测数组 |
| 71 | + * |
| 72 | + * @Author xuyangyang |
| 73 | + * @Describe |
| 74 | + * @date 2017年2月20日 |
| 75 | + * @param newCapacity |
| 76 | + */ |
| 77 | + public void ensureCapacity(int newCapacity) { |
| 78 | + if (newCapacity < size) { |
| 79 | + return; |
| 80 | + } |
| 81 | + Object[] old = elementData;// |
| 82 | + |
| 83 | + elementData = new Object[newCapacity];// 建立新的数组 |
| 84 | + |
| 85 | + for (int i = 0; i < old.length; i++) { |
| 86 | + elementData[i] = old[i]; |
| 87 | + } |
| 88 | + |
| 89 | + } |
| 90 | + |
| 91 | + private class InnerIterator implements MyIterator { |
| 92 | + |
| 93 | + private int current = 0; |
| 94 | + |
| 95 | + public boolean hasNext() { |
| 96 | + return current < size(); |
| 97 | + } |
| 98 | + |
| 99 | + @Override |
| 100 | + public Object next() { |
| 101 | + if (!hasNext()) { |
| 102 | + throw new NoSuchElementException(); |
| 103 | + } |
| 104 | + return elementData[current++]; |
| 105 | + } |
| 106 | + |
| 107 | + public void remove() { |
| 108 | + MyArrayList.this.remove(--current); |
| 109 | + } |
| 110 | + |
| 111 | + } |
| 112 | + |
| 113 | +} |
0 commit comments