publicArray(int capacity){ data = (E[]) new Object[capacity]; size = 0; }
publicArray(){ this(10); }
publicintgetSize(){ return size; }
publicintgetCapacity(){ return data.length; }
publicbooleanisEmpty(){ return size == 0; }
// 在index索引位置,增加一个元素e publicvoidadd(int index, E e){ if (index < 0 || index > size) { thrownew IllegalArgumentException("Add failed. Array is full"); } if (size == data.length) { resize(2 * data.length); } for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = e; size++; }
publicvoidaddLast(E e){ add(size, e); }
publicvoidaddFirst(E e){ add(0, e); }
// 根据index索引位置查找元素 public E get(int index){ if (index < 0 || index >= size) thrownew IllegalArgumentException("Find failed. Index is illegal"); return data[index]; }
public E getLast(){ return data[size - 1]; }
public E getFirst(){ return data[0]; }
// 修改index索引位置元素为e publicvoidset(int index, E e){ if (index < 0 || index >= size) thrownew IllegalArgumentException("Find failed. Index is illegal"); data[index] = e; }
// 判断数组中是否存在某元素e publicbooleancontains(E e){ for (int i = 0; i < size; i++) { if (data[i].equals(e)) returntrue; } returnfalse; }
// 查找数组中元素e所在的索引,若不存在,返回-1 publicintfind(E e){ for (int i = 0; i < size; i++) { if (data[i] == e) return i; } return -1; }
// 删除index索引的元素,并返回元素值 public E remove(int index){ if (index < 0 || index >= size) thrownew IllegalArgumentException("Remove failed. Index is illegal"); E ret = data[index]; for (int i = index; i < size - 1; i++) { data[i] = data[i + 1]; } size--; // data[size] = null; if (size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return ret; }
public E removeFirst(){ return remove(0); }
public E removeLast(){ return remove(size - 1); }
// 从数组中删除元素e(第一次发现到的) publicvoidremoveElement(E e){ int index = find(e); if (index != -1) remove(index); }
@Override public String toString(){ StringBuilder res = new StringBuilder(); res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length)); res.append("["); for (int i = 0; i < size; i++) { res.append(data[i]); if (i != size - 1) { res.append(", "); } } res.append("]"); return res.toString(); }
// 容量不够自动扩容,容量减小到一定程度,缩容 privatevoidresize(int newCapacity){ E[] newData = (E[]) new Object[newCapacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; }