手写ArrayList实例

心已入冬 提交于 2020-02-12 02:37:08

效果

在这里插入图片描述

代码块:

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());

    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!