// 获取index索引位置的位置 public E get(int index)throws IllegalAccessException { if (index < 0 || index >= size) { thrownew IllegalAccessException("Failed failed.Array is full"); } return data[index]; }
// 修改index索引位置的元素为e publicvoidset(int index, E e){ data[index] = e; }
// 查找数组中是否有元素e publicbooleancontains(E e){ for (int i = 0; i < size; i++) { if (data[i].equals(e)) { returntrue; } } returnfalse; }
// 查找一个数的下标 publicintfind(E e){ for (int i = 0; i < size; i++) { if (data[i].equals(e)) { return i; } } return -1; }
// 在指定位置上增加一个元素 publicvoidadd(int index, E e)throws IllegalAccessException {
if (index < 0 || index > size) { thrownew IllegalAccessException("Add failed."); } 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++; }
privatevoidresize(int newCapacity){ E[] newData = (E[])new Object[newCapacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; }
// 移除数组中的一个元素,并返回移除的数 public E remove(int index)throws IllegalAccessException { if (index < 0 || index > size) { thrownew IllegalAccessException("Remove failed."); } E ret = data[index]; for (int i = index + 1; i < size; i++) { data[i - 1] = data[i]; } size--; // 这里利用懒策略,并且数组的缩容不能为0 if(size == data.length / 4 && data.length / 2 != 0 ) { resize(data.length / 2); } return ret; }
// 从数组中删除第一个元素 public E removeFirst()throws IllegalAccessException { return remove(0); }
// 从数组中删除最后一个元素 public E removeLast()throws IllegalAccessException { return remove(size - 1); }
// 删除一个元素 publicvoidremoveElement(E e)throws IllegalAccessException { 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(','); }