模拟ArrayList自定义一个泛型类数组类可以实现数组初始化,添加元素,获取元素,删除元素等操作
时间: 2023-08-07 08:04:56 浏览: 169
好的,我来为您实现一个泛型类数组类:
```java
public class MyArrayList<E> {
private static final int DEFAULT_CAPACITY = 10;
private Object[] data;
private int size;
public MyArrayList() {
this(DEFAULT_CAPACITY);
}
public MyArrayList(int capacity) {
data = new Object[capacity];
size = 0;
}
public void add(E element) {
ensureCapacity(size + 1);
data[size++] = element;
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return (E) data[index];
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
System.arraycopy(data, index + 1, data, index, size - index - 1);
data[--size] = null;
}
public int size() {
return size;
}
private void ensureCapacity(int minCapacity) {
if (minCapacity > data.length) {
int newCapacity = data.length * 2;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
data = Arrays.copyOf(data, newCapacity);
}
}
}
```
这个类实现了一个简单的动态数组,可以添加元素、获取元素、删除元素,并且当数组大小不足时能够自动扩容。使用方法和 `ArrayList` 类似,例如:
```java
MyArrayList<String> list = new MyArrayList<>();
list.add("hello");
list.add("world");
System.out.println(list.get(0)); // 输出 "hello"
list.remove(0);
System.out.println(list.size()); // 输出 1
```
阅读全文