数组

数据结构

1 数组 不带泛型



```java
// 自定义 数组类
public class myArray {

    // myArray数组 对象 data
    private int[] data;
    // myArray数组 元素个数
    private int size;

    public myArray(int capacity) {
        data = new int[capacity];
    }

    public myArray() {
        this(10);
    }

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

    // 特殊的方法 容量 是否空 数据个数  包含
    public int getCapacity() {
        return data.length;
    }

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

    public int getSize() {
        return size;
    }

    public boolean contain(int e) {
        for (int i = 0; i < size; i++) {
            if (data[i] == e) {
                return true;
            }
        }
        return false;
    }

    // 添加
    public void add(int index, int e) {
        if (index > size || index < 0) {
            throw new IllegalArgumentException("add failed the index is illegal!");
        }
        if (size == data.length) {
            // data.length 是构造函数开辟的容量 已经和 元素个数想等
            throw new IllegalArgumentException("add failed myArray is full!!");
        }
        // 索引内部添加, index 到 size - 1 (size 是元素个数) 全部后移
        for (int i = size - 1; i > index - 1; i--) {
            data[i + 1] = data[i];
        }
        data[index] = e;
        size++;
    }

    // 特殊 add
    public void addFirst(int e) {
        add(0, e);
    }

    public void addLast(int e) {
        // 原有size个元素,索引只到size-1; size刚好是最高位
        add(size, e);
    }

    // 查询 查找元素,返回索引 第一个找到的元素
    public int find(int e) {
        for (int i = 0; i < size; i++) {
            if (data[i] == e) {
                return i;
            }
        }
        return -1;
    }
    

    // 删除
    public int remove(int index) {
        if (index > size || index < 0) {
            throw new IllegalArgumentException("remove failed the index is illegal!");
        }
        if (size == 0) {
            throw new IllegalArgumentException("remove failed myArray is empty!!");
        }
        int result = data[index];
        // index删除,index+1 到 size-1 全都左移1位
        for (int i = index + 1; i < size; i++) {
            data[i - 1] = data[i];
        }
        size--;
        return result;
    }
    public int removeFist() {
        return remove(0);
    }
    public int removeLast() {
        return remove(size-1);
    }
    // 试图删除一个元素 
    public  boolean removeElement(int e) {
        // find() 返回的是索引
        int index = find(e);
        if (index == -1) {
            return false;
        } else {
            return true;
        }
    }
}

posted @ 2021-12-28 21:26  وق  阅读(39)  评论(0)    收藏  举报