任务描述
自己写一个ArrayList, 模拟java给我们提供的ArrayList
要求提供的方法为:remove,add,get,size.
暂时该我们的list只能处理int类型。它看起来像这个样子来构造和使用
MyArrayList list = new MyArrayList();
或
MyArrayList list = new MyArrayList(10);
for(int i = 0; i < 1000; i ++) {
list.add(i);
}
list.get(2);
list.remove(3);
list.size();
代码部分
package com.java.stage2.lesson10;
import java.util.Arrays;
/**
* @author lesous
* @date 2023/03/31
*/
public class MyArrayList {
private int[] list;
private int capacity;
private int amount;
public MyArrayList(int initialcapacity) {
this.list = new int[initialcapacity];
this.capacity = initialcapacity;
this.amount = 0;
}
public MyArrayList() {
this.list = new int[10];
this.capacity = 10;
this.amount = 0;
}
public int size() {
return amount;
}
//每次add元素之前检测MyArrayList是否需要扩容
public boolean add(int element) {
if (capacity - amount <= 0) {
grow(amount);
}
list[amount] = element;
amount++;
return true;
}
public boolean add(int index, int element) {
amount++;
if (capacity < amount) {
grow(amount);
}
if (index > amount || index < 0) {
System.out.println("超出索引");
return false;
}
for (int i = amount; i > index - 1; i--) {
if (amount != index) {
list[i] = list[i - 1];
}
}
list[index] = element;
return true;
}
//删除指定索引处的元素
public boolean remove(int index) {
if (index > amount || index < 0) {
System.out.println("超出索引");
return false;
}
for (int i = index; i < amount; i++) {
list[i] = list[i + 1];
}
amount--;
return true;
}
//取得索引处元素
public int get(int index) {
if (index < 0 || index >= amount) {
System.out.println("超出索引");
}
return list[index];
}
//打印所有元素
public void printAll() {
for (int i = 0; i < amount; i++) {
System.out.print(list[i]);
if (i != amount - 1) {
System.out.print(",");
}
}
System.out.println();
}
//MyArrayList 扩容
private void grow(int amount) {
int oldCapacity = list.length;
int newCapacity = oldCapacity + 2;
if (newCapacity - amount < 0) {
newCapacity = amount;
}
list = Arrays.copyOf(list, newCapacity);
}
}
MyArrayList测试
package com.java.stage2.lesson10;
import java.util.ArrayList;
/**
* @author lesous
* @date 2023/03/31
*/
public class TestMyArrayList {
public static void main(String[] args) {
MyArrayList list = new MyArrayList();
for(int i = 0; i < 1000; i ++) {
list.add(i);
}
list.printAll();
System.out.println("MyArrayList的长度为 "+list.size());
System.out.println("list.get(2)的元素为 "+list.get(2));
list.remove(3);
list.printAll();
System.out.println("删除索引处元素后MyArrayList的长度为 "+list.size());
}
}