ArrayList 要求:包括add、get、size、indexOf、remove方法的实现。
时间: 2023-07-10 17:16:23 浏览: 87
好的,我可以帮你实现一个简单的 ArrayList,满足你的要求。以下是代码实现:
```java
public class ArrayList<T> {
private Object[] elements;
private int size;
private final int DEFAULT_CAPACITY = 10;
public ArrayList() {
elements = new Object[DEFAULT_CAPACITY];
size = 0;
}
public void add(T element) {
if (size == elements.length) {
Object[] newElements = new Object[2 * size];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
elements[size++] = element;
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return (T) elements[index];
}
public int size() {
return size;
}
public int indexOf(T element) {
if (element == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (element.equals(elements[i])) {
return i;
}
}
}
return -1;
}
public T remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
T removedElement = (T) elements[index];
System.arraycopy(elements, index + 1, elements, index, size - index - 1);
size--;
elements[size] = null;
return removedElement;
}
}
```
这个 ArrayList 实现了泛型,可以存储任意类型的元素。当数组已满时,会自动扩容。同时,get、indexOf、remove 方法也会检查越界情况,确保程序的健壮性。
阅读全文