定义一个泛型类MyArrayList,实现数组列表的基本操作:add、remove、get、size。
时间: 2024-05-07 13:16:29 浏览: 21
很高兴回答您的问题!下面是泛型类MyArrayList的实现代码:
```java
public class MyArrayList<T> {
private T[] elementData;
private int size;
public MyArrayList() {
this.elementData = (T[]) new Object[10];
this.size = 0;
}
public boolean add(T e) {
if (size == elementData.length) {
T[] newElementData = (T[]) new Object[size * 2];
System.arraycopy(elementData, 0, newElementData, 0, size);
elementData = newElementData;
}
elementData[size++] = e;
return true;
}
public boolean remove(int index) {
if (index >= size || index < 0) {
return false;
}
System.arraycopy(elementData, index + 1, elementData, index, size - index - 1);
size--;
return true;
}
public T get(int index) {
if (index >= size || index < 0) {
return null;
}
return elementData[index];
}
public int size() {
return size;
}
}
```
该实现使用了数组作为底层存储结构,能够实现基本的数组列表操作。希望对您有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)