线性结构List接口的实现类
时间: 2023-08-16 07:04:21 浏览: 43
下面是一个基于数组实现的线性结构List接口的实现类(Java语言):
```
public class ArrayList<E> implements List<E> {
private E[] array; // 存储元素的数组
private int size; // 当前元素个数
// 构造函数:初始化数组大小为10
public ArrayList() {
this(10);
}
// 构造函数:初始化数组大小为initialCapacity
public ArrayList(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
array = (E[]) new Object[initialCapacity];
}
// 添加元素到指定位置
@Override
public void add(int index, E element) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
if (size == array.length) {
ensureCapacity(size + 1);
}
System.arraycopy(array, index, array, index + 1, size - index);
array[index] = element;
size++;
}
// 添加元素到末尾
@Override
public boolean add(E element) {
if (size == array.length) {
ensureCapacity(size + 1);
}
array[size++] = element;
return true;
}
// 删除指定位置的元素
@Override
public E remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
E oldValue = array[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(array, index + 1, array, index, numMoved);
}
array[--size] = null; // 将最后一个元素设为null,便于垃圾回收
return oldValue;
}
// 获取指定位置的元素
@Override
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return array[index];
}
// 设置指定位置的元素
@Override
public E set(int index, E element) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
E oldValue = array[index];
array[index] = element;
return oldValue;
}
// 返回元素个数
@Override
public int size() {
return size;
}
// 判断是否为空
@Override
public boolean isEmpty() {
return size == 0;
}
// 扩容数组
private void ensureCapacity(int minCapacity) {
int oldCapacity = array.length;
if (minCapacity > oldCapacity) {
E[] oldArray = array;
int newCapacity = (oldCapacity * 3) / 2 + 1;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
array = (E[]) new Object[newCapacity];
System.arraycopy(oldArray, 0, array, 0, size);
}
}
}
```
这个实现类使用了泛型,可以存储任意类型的元素。其中,add() 方法有两个重载,一个是添加元素到指定位置,一个是添加元素到末尾;remove() 方法删除指定位置的元素;get() 方法获取指定位置的元素;set() 方法设置指定位置的元素;size() 方法返回元素个数;isEmpty() 方法判断是否为空;ensureCapacity() 方法扩容数组。注意,数组下标从0开始。