手寫ArrayList實例

效果

在這裏插入圖片描述

代碼塊:

package com.example.javase;

/**
 * @Description: ArrayList demo
 * @author: YZD
 * @Date: 2020-02-11 15:48
 * @Version: 1.0
 */
public class arrayListDemo<E> {
    /**
     * 特點:
     * 查詢效率高(index)
     * 增刪效率低(System.arraycopy)
     * 線程不安全
     * <p>
     * 數組擴容
     */

    private Object[] elementData;
    private int size = 0;

    //默認長度
    private static final int DEAFULT_CAPACITY = 10;

    public arrayListDemo() {
        elementData = new Object[DEAFULT_CAPACITY];
    }

    public Object[] getElementData() {
        return elementData;
    }

    public void setElementData(Object[] elementData) {
        this.elementData = elementData;
    }

    public void add(E object) {
        //擴容
        if (size == elementData.length) {
            Object[] newObj = new Object[size + (size >> 1)];
            System.arraycopy(elementData, 0, newObj, 0, elementData.length);
            elementData = newObj;
        }
        elementData[size++] = object;
    }

    public Object get(int index) throws Exception {
        check(index);
        return elementData[index];
    }

    public void set(E e, int index) throws Exception {
        check(index);
        elementData[index] = e;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }


    public void remove(E e) throws Exception {
        for (int i = 0; i < size; i++) {
            if (e.equals(get(i))) {
                // 刪除
                remove(i);
            }
        }
    }

    public void remove(int index) throws Exception {
        check(index);
        System.arraycopy(elementData, index + 1, elementData, index, elementData.length - index - 1);
        elementData[--size] = null;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        int count = 0;
        for (int i = 0; i < elementData.length; i++) {
            if (elementData[i] != null) {
                count += elementData[i].toString().length() + 1;
                stringBuilder.append(elementData[i]).append(",");
            }
        }
        stringBuilder.setCharAt(count, ']');
        return stringBuilder.toString();
    }

    private void check(int index) throws Exception {
        if (index < 0 || index > size) {
            throw new Exception("索引不合法");
        }
    }

    public static void main(String[] args) throws Exception {
        arrayListDemo list = new arrayListDemo();
        list.add("a");
        list.add("b");
        list.add("c");
        System.out.println(list.toString());
//        list.set("set", 0);
        System.out.println(list.get(0));
        list.remove(1);
        list.remove("a");
        System.out.println(list.toString());

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章