定义一个泛型类MyArrayList,实现数组列表的基本操作:add、remove、get、size。
时间: 2024-01-31 17:04:31 浏览: 36
好的,下面是一个简单的实现:
```java
public class MyArrayList<T> {
private T[] array;
private int size;
public MyArrayList() {
array = (T[]) new Object[10];
size = 0;
}
public void add(T element) {
if (size == array.length) {
T[] newArray = (T[]) new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
array[size++] = element;
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
System.arraycopy(array, index + 1, array, index, size - index - 1);
array[--size] = null;
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
return array[index];
}
public int size() {
return size;
}
}
```
这个实现使用了一个泛型数组来存储元素,并且在需要时动态调整数组的大小。add() 方法将元素添加到数组末尾,如果数组已满则先扩展数组。remove() 方法删除指定位置的元素,并将后面的元素向前移动。get() 方法返回指定位置的元素。size() 方法返回数组中元素的个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)