顺序表增删改查(java)基础
java数据结构中顺序表的基本操作方法(增删改查)
public class ArrayList<E> {
// 当前存储的元素数量
private int size = 0;
// 初始容量大小
private int capacity = 10;
// 存储元素的底层数组(使用Object数组支持泛型)
private Object[] array = new Object[capacity];
public void add(E temp, int index) {
// 检查索引合法性(允许在末尾插入,即index=size)
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("插入位置非法,0~" + size);
// 检查是否需要扩容(当元素数量达到容量上限时)
if (size >= capacity) {
// 扩容策略:原容量的1.5倍(右移1位相当于除以2)
int newCapacity = capacity + (capacity >> 1);
// 创建新数组并复制原有元素
Object[] newArray = new Object[newCapacity];
System.arraycopy(array, 0, newArray, 0, size);
// 替换底层数组引用
array = newArray;
capacity = newCapacity;
}
// 将插入位置之后的元素依次后移一位
for (int i = size; i > index; i--)
array[i] = array[i - 1];
// 插入新元素并更新大小
array[index] = temp;
size++;
}
public E remove(int index) {
// 检查索引合法性
if (index < 0 || index > size - 1)
throw new IndexOutOfBoundsException("删除位置非法,0~" + (size - 1));
// 获取并保存待删除元素
E e = (E) array[index];
// 将删除位置之后的元素依次前移一位
for (int i = index; i < size - 1; i++)
array[i] = array[i + 1];
// 更新大小(原最后一个元素已被覆盖,无需显式置为null)
size--;
return e;
}
public void set(int index, E element) {
// 检查索引合法性
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("修改位置非法,0~" + (size - 1));
// 直接替换指定位置的元素
array[index] = element;
}
public E get(int index) {
// 检查索引合法性
if (index < 0 || index > size - 1)
throw new IndexOutOfBoundsException("获取位置非法,0~" + (size - 1));
// 返回指定位置元素(需要类型转换回泛型类型)
return (E) array[index];
}
public String toString() {
// 使用StringBuilder高效拼接字符串
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++)
builder.append(array[i]).append(" ");
// 转换为字符串并返回
return builder.toString();
}
} 版权申明
本文系作者 @吃了一只小羊 原创发布在Hello World站点。未经许可,禁止转载。
暂无评论数据