简单手写的ArrayList

一、简单的增删改查

package com.自己实现ArrayList;

import java.util.Arrays;

public class MyArrayList01 {
   private Object[] array= new Object[10];
   private int size;

    public Object getArray() {
        return array;
    }


    public void setArray(Object[] array) {
        this.array = array;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public MyArrayList01() {
    }

    public MyArrayList01(int size) {
        this.size = size;
    }

    public MyArrayList01(Object[] array, int size) {
        this.array = array;
        this.size = size;
    }

    public void add(Object oj){
        if(size<array.length){
            array[size]=oj;
            size++;
        }else{
            int oldSize=array.length;
            int newSize=oldSize+oldSize/2;
            Object[] newArray= new Object[newSize];
            System.arraycopy(array,0,newArray,0,oldSize);
            array=newArray;
            array[size]=oj;
            size++;
        }
    }

    public void adds(int index,Object oj){
        if(index<array.length){
            for (int i = size; i >index; i--) {
                array[i]=array[i-1];
            }
            array[index]=oj;
            size++;
        }else{
            int oldSize=array.length;
            int newSize=oldSize+oldSize/2;
            Object[] newArray= new Object[newSize];
            System.arraycopy(array,0,newArray,0,oldSize);
            array=newArray;
            array[size]=oj;
            size++;
        }
    }

    public void remove(){
        array[size-1]=null;
        size--;
    }

    public void removes(int index){
        for (int i = index; i < size; i++) {
            array[i]=array[i+1];
        }
        size--;
    }

    public void change(int index,Object oj){
        array[index]=oj;
    }

    @Override
    public String toString() {
        return "MyArrayList01{" +
                "array=" + Arrays.toString(array) +
                ", size=" + size +
                '}';
    }

}

二、测试类

package com.自己实现ArrayList;

public class Test {
    public static void main(String[] args) {
        MyArrayList01 myArrayList01 = new MyArrayList01();
        for (int i = 0; i <20 ; i++) {
            myArrayList01.add(i);
        }
        System.out.println(myArrayList01.toString());

        myArrayList01.remove();
        System.out.println(myArrayList01.toString());

        myArrayList01.change(1,3);
        System.out.println(myArrayList01);

        myArrayList01.removes(5);
        System.out.println(myArrayList01);

        myArrayList01.adds(3,0);
        System.out.println(myArrayList01.toString());

        myArrayList01.adds(21,10);
        System.out.println(myArrayList01.toString());
    }
}

三、测试结果

posted @ 2021-07-09 13:02  GzhAnkh  阅读(64)  评论(0)    收藏  举报