1、手写一个ArrayList类:
public class DIYArrayList<T> implements Iterable<T> {
private T[] data;//存储元素数组
private int size;//元素个数
//无参构造:默认大小为10
public DIYArrayList() {
this(10);
}
//有参构造
public DIYArrayList(int campcity) {
if (campcity < 0){
try {
throw new IllegalAccessException("参数异常");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
data = (T[]) new Object[campcity];
size = 0;
}
}
2、实现简单的方法
- 判满
private boolean isFull() {
return size == data.length;
}
- 扩容:此处采用的也是1.5倍扩容
private void grow() {
int newLength = size+size>>1;
data = Arrays.copyOf(data, newLength);
}
- 范围判断:参数合法性校验
private boolean checkRange(int index) {
if (index< 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return true;
}
- 添加元素
public boolean add(T e) {
if (isFull()) {
grow();
}
data[size++]=e;
return true;
}
- 获取元素
public T get(int index) {
checkRange(index);
return data[index];
}
- 删除指定位置的元素
public T remove(int index) {
checkRange(index);
T v = data[index];
int mov = size -index-1;
System.arraycopy(data,index+1,data,index,mov);
data[--size] = null;
return v;
}
- 删除元素:需注意的是,元素值为null和非null判断相等的方式的不同
public boolean remove (T e) {
if (e == null) {
for (int i = 0; i < size; i++) {
if (data[i] == null) {
int mov = size -i-1;
System.arraycopy(data, i+1, data,i,mov);
data[--size] = null;
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
if (e.equals(data[i])) {
int mov = size -i-1;
System.arraycopy(data, i+1, data,i,mov);
data[--size] = null;
return true;
}
}
}
return false;
}
- 重写toString方法
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < size; i++) {
buffer.append(data[i]+" ");
}
return buffer.toString();
}
测试及结果
public static void main(String[] args) {
DIYArrayList<Integer> arrayList = new DIYArrayList<>(30);
Random random = new Random();
for (int i = 0; i < 20; i++) {
arrayList.add(Integer.valueOf(random.nextInt(50)));
}
arrayList.add(12);
arrayList.add(56);
arrayList.add(34);
arrayList.add(56);
System.out.println("原始数组:" + arrayList);
System.out.println(arrayList.get(2)); //打印2号索引位置的元素
arrayList.remove(1); //删除1号索引位置的元素
System.out.println(arrayList);
arrayList.remove(Integer.valueOf(56)); //删除值为34的元素
System.out.println(arrayList);
}
可以看到remove()删除元素时只会删除第一次出现的元素