ementData, capacity);
? ? ? ? }
? ? }
? ? // 在顺序表的末尾添加一个元素
? ? public void add(T element) {
? ? ? ? insert(element, size);
? ? }
? ? // 删除顺序表中指定索引处的元素
? ? public T delete(int index) {
? ? ? ? if (index < 0 || index > size - 1)
? ? ? ? ? ? throw new IndexOutOfBoundsException("顺序表索引越界");
? ? ? ? T oldValue = (T) elementData[index];
? ? ? ? int numMoved = size - index - 1;// 计算需要移动的元素个数
? ? ? ? if (numMoved > 0) {
? ? ? ? ? ? System.arraycopy(elementData, index + 1, elementData, index,
? ? ? ? ? ? ? ? ? ? numMoved);
? ? ? ? }
? ? ? ? elementData[--size] = null;// 让垃圾回收器及时回收,避免内存泄露
? ? ? ? return oldValue;
? ? }
? ? // 删除顺序表中的最后一个元素
? ? public T remove() {
? ? ? ? return delete(size - 1);
? ? }
? ? // 判断顺序表是否为空表
? ? public boolean empty() {
? ? ? ? return size == 0;
? ? }
? ? // 清空顺序表
? ? public void clear() {
? ? ? ? Arrays.fill(elementData, null);// 将数组elementData中的每个元素都赋值null
? ? ? ? size = 0;
? ? }
? ? public String toString() {
? ? ? ? if (size == 0)
? ? ? ? ? ? return "[]";
? ? ? ? else {
? ? ? ? ? ? StringBuilder sb = new StringBuilder("[");
? ? ? ? ? ? for (int i = 0; i < size; i++)
? ? ? ? ? ? ? ? sb.append(elementData[i].toString() + ", ");
? ? ? ? ? ? int len = sb.length();
? ? ? ? ? ? // 删除由于上面for循环中最后添加的多余的两个字符 (一个是逗号,一个是空格符号)
? ? ? ? ? ? return sb.delete(len - 2, len).append("]").toString();
? ? ? ? }
? ? }
}