定义一个泛型类MyArrayList,实现数组列表的基本操作: add、remove、get、size
时间: 2024-01-01 15:06:09 浏览: 114
用ArrayList实现用户信息的添加,删除,更新,查询
5星 · 资源好评率100%
```java
public class MyArrayList<T> {
private Object[] array;
private int size;
public MyArrayList() {
this.array = new Object[10];
this.size = 0;
}
public void add(T element) {
if (size == array.length) {
Object[] newArray = 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();
}
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();
}
return (T) array[index];
}
public int size() {
return size;
}
}
```
使用示例:
```java
MyArrayList<String> list = new MyArrayList<>();
list.add("foo");
list.add("bar");
list.add("baz");
System.out.println(list.get(1)); // 输出 "bar"
list.remove(0);
System.out.println(list.size()); // 输出 2
```
阅读全文