public class ArrayListDemo {public int size=0;//当前数组容量public int capacity=2;//默认容量public Object[] objects = new Object[capacity];public ArrayListDemo() {}public void add(Object object) {//检查数组是否已经装满,如果数组装满,数组容量扩大一倍if(capacity==size){capacity = this.capacity*2;objects = Arrays.copyOf(objects,capacity);}//添加数据objects[size++]=object;}public void delete(Object object) {//删除指定元素//遍历数组int temp = 0;for(int i = 0;i<size;i++){if(object==objects[i]){temp = i;break;}}for(int j=temp;j<size;j++){objects[temp]=objects[temp+1];}size--; // System.arraycopy(objects, temp+1, objects, temp, size-temp); // size--; }@Overridepublic String toString() {//重写方法String str = "[";for (int i = 0;i<size;i++){str=str+" "+objects[i];}str=str+" "+"]";return str;}public void set(int i, Object object) {//修改数组if(i<0||i>capacity){System.out.println("超出数组大小");}for(int j=0;j<capacity;j++){if(i==j){objects[i-1]=object;break;}}} }
public class ArrayListTest {public static void main(String[] args) {ArrayListDemo arrayListDemo = new ArrayListDemo();arrayListDemo.add(1);arrayListDemo.add("AA");arrayListDemo.add("##");arrayListDemo.add(6);arrayListDemo.add(5);System.out.println(arrayListDemo.size);//测试数组当前元素数量System.out.println(arrayListDemo);//测试查询//arrayListDemo.delete(6);//测试删除//System.out.println(arrayListDemo);//arrayListDemo.set(3,"hello");//测试修改//System.out.println(arrayListDemo); } }