1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
public class MyArrayList<T> implements MyList<T> { private T[] elements;
private int size = 0;
private int capacity = 10;
public MyArrayList(int capacity) { this.capacity = capacity;
elements = (T[]) new Object[capacity]; }
public MyArrayList() { elements = (T[]) new Object[capacity]; }
@Override public void add(T element) { if (size == capacity) { capacity *= 2; T[] newArr = (T[]) new Object[capacity]; for (int i = 0; i < size; i++) { newArr[i] = elements[i]; } elements = newArr; } elements[size++] = element; }
@Override public void delete(T element) { int index = indexOf(element); if (index >= 0) { delete(index); } }
@Override public void delete(int index) { for (int i = index; i < size - 1; i++) { elements[i] = elements[i + 1]; } elements[size - 1] = null; size--; }
@Override public void update(int index, T newElement) { elements[index] = newElement; }
@Override public boolean contains(T target) { return indexOf(target) >= 0; }
@Override public T at(int index) { return elements[index]; }
@Override public int indexOf(T element) { for (int i = 0; i < size; i++) { if (elements[i].equals(element)) { return i; } } return -1; }
@Override public String toString() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < size; i++) { sb.append(elements[i] + (i == size - 1 ? "" : " , ")); } sb.append("]"); return sb.toString(); }
@Override public boolean hasNext() { return false; }
@Override public T next() { return null; } }
|