数组

什么是数组?

数组就是把数据码成一排进行存放

需要注意的是数组的索引是从0开始

使用Java中的数组

public static void main(String[] args) {
        //定义数组以及长度为10
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
        //定义数组以及数据
        int[] scores = new int[]{100, 99, 98};
        //修改第0个值为10
        scores[0] = 10;
        for (int score : scores) {
            System.out.println(score);
        }
}

封装属于我们的数组

  • 数组最大的优点:快速查询。 scores[2]
  • 数组最好应用于"索引有语意"的情况。
  • 但是并非所有有语意的索引都适用于数组
  • 例如:身份证号,如果想用身份证号来当索引的话,我们要开辟一个很大的空间。

索引没有语意的情况下,如何表示没有元素?

如何添加元素?如何删除元素?

基于Java的数组,二次封装属于我们自己的数组类。

public class Array {
        private int[] data;
        private int size;

        //无参数的构造函数,默认的数组容量大小为10
        public Array() {
            this(10);
        }

        //构造函数,传入数组的容量capacity构造Array
        public Array(int capacity) {
            data = new int[capacity];
            size = 0;
        }

        //获取数组中的元素个数
        public int getSize() {
            return size;
        }

        //获取数组的容量
        public int getCapacity() {
            return data.length;
        }

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

向数组中添加元素

一开始,数组的size是0,如果我们想增加值为66,数据将会存放在索引为0的位置,然后size进行自增。

public void addLast(int e){
        if(size >= data.length){
            throw new ArrayIndexOutOfBoundsException("AddLast failed. Array is full");
        }
        data[size] = e;
        size ++;
    }

但是,如果我们想在指定位置插入数据呢?

如果我们要把77插入到如图索引为1的位置,我们首先需要将100往后挪一位,然后将99、88依次后挪一位,然后腾出位置给77进行插入。插入之后不要忘记将size自增

public void addLast(int e) {
        add(size, e);
}

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

public void add(int index, int e) {
    if (size >= data.length) {
        throw new ArrayIndexOutOfBoundsException("add failed. Array is full.");
    }
    if (index < 0 || index > size) {
        throw new IllegalArgumentException("add failed. Require index >= 0 and index <= size.");
    }
    //将大于index的元素都进行索引加一
    for (int i = size - 1; i >= index; i--) {
        data[i + 1] = data[i];
    }
    data[index] = e;
    size++;
}

顺便我们重写一下toString方法,测试一下我们的Array类。

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append("[");
        for (int i = 0; i < size; i++) {
            res.append(data[i]);
            if (i != size - 1) {
                res.append(", ");
            }
        }
        res.append("]");
        return res.toString();
    }
 public static void main(String[] args) {
        Array array = new Array(20);
        for (int i = 0; i < 10; i++) {
            array.addLast(i);
        }
        array.addLast(15);
        array.addFirst(17);
        array.add(5,18);
        System.out.println(array);
}
Array: size = 13 , capacity = 20[17, 0, 1, 2, 3, 18, 4, 5, 6, 7, 8, 9, 15]

查询元素和修改元素

    //获取index索引位置的元素
    public int get(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("get failed. Require index >= 0 and index < size.");
        }
        return data[index];
    }

    //修改index索引位置的元素
    public void set(int index, int e) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("set failed. Require index >= 0 and index < size.");
        }
        data[index] = e;
    }

包含,搜索和删除

    //查找数组中是否有元素e
    public boolean contains(int e){
        for (int i = 0; i < size; i++) {
            if (data[i]== e){
                return true;
            }
        }
        return false;
    }
    //查找数组中元素e所在的索引,如果不存在元素e,则返回-1
    public int find(int e){
        for (int i = 0; i < size; i++) {
            if (data[i]== e){
                return i;
            }
        }
        return -1;
    }

如果我们想删除指定位置的元素,我们需要将大于指定位置的索引全部依次往前挪一位。

当数据挪完以后呢,我们不需要删除索引为4的数据,只需要将索引减一指向4即可。

因为用户是永远看不到size的值是多少,只能查询到size - 1的值。

    //从数组中删除index位置的元素,并返回删除的元素
    public int remove(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("remove failed. Require index >= 0 and index < size.");
        }
        int ret = data[index];
        for (int i = index + 1; i < size; i++) {
            data[i - 1] = data[i];
        }
        size --;
        return ret;
    }
    //从数组中删除最后一个元素,并返回删除的元素
    public int removeLast() {
        return remove(size -1);
    }
    //从数组中删除第一个元素,并返回删除的元素
    public int removeFirst() {
        return remove(0);
    }
    //从数组中删除元素e
    public void removeElement(int e) {
        int index = find(e);
        if (index != -1){
            remove(index);
        }
    }

目前为止,我们这个Array只能承载int类型,我们不可能为每个类型创建一个数组类,所以我们要使用泛型来解决此问题。

使用泛型

这里我就直接放出替换好的Array类

public class Array<E> {
        private E[] data;
        private int size;
        //无参数的构造函数,默认的数组容量大小为10
        public Array() {
            this(10);
        }
        //构造函数,传入数组的容量capacity构造Array
        public Array(int capacity) {
            data = (E[]) new Object[capacity];
            size = 0;
        }
        //获取数组中的元素个数
        public int getSize() {
            return size;
        }
        //获取数组的容量
        public int getCapacity() {
            return data.length;
        }
        public boolean isEmpty() {
            return size == 0;
        }
        public void addLast(E e) {
            add(size, e);
        }
        public void addFirst(E e) {
            add(0, e);
        }
        public void add(int index, E e) {
            if (size >= data.length) {
                throw new ArrayIndexOutOfBoundsException("add failed. Array is full.");
            }
            if (index < 0 || index > size) {
                throw new IllegalArgumentException("add failed. Require index >= 0 and index <= size.");
            }
            //将大于index的元素都进行索引加一
            for (int i = size - 1; i >= index; i--) {
                data[i + 1] = data[i];
            }
            data[index] = e;
            size++;
        }
        //获取index索引位置的元素
        public E get(int index) {
            if (index < 0 || index >= size) {
                throw new IllegalArgumentException("get failed. Require index >= 0 and index < size.");
            }
            return data[index];
        }
        //修改index索引位置的元素
        public void set(int index, E e) {
            if (index < 0 || index >= size) {
                throw new IllegalArgumentException("set failed. Require index >= 0 and index < size.");
            }
            data[index] = e;
        }
        //查找数组中是否有元素e
        public boolean contains(E e) {
            for (int i = 0; i < size; i++) {
                if (data[i] == e) {
                    return true;
                }
            }
            return false;
        }
        //查找数组中元素e所在的索引,如果不存在元素e,则返回-1
        public int find(E e) {
            for (int i = 0; i < size; i++) {
                if (data[i] == e) {
                    return i;
                }
            }
            return -1;
        }
        //从数组中删除index位置的元素,并返回删除的元素
        public E remove(int index) {
            if (index < 0 || index >= size) {
                throw new IllegalArgumentException("remove failed. Require index >= 0 and index < size.");
            }
            E ret = data[index];
            for (int i = index + 1; i < size; i++) {
                data[i - 1] = data[i];
            }
            size --;
            //回收当前无用的数据
            data[size] = null;
            return ret;
        }
        //从数组中删除最后一个元素,并返回删除的元素
        public E removeLast() {
            return remove(size -1);
        }
        //从数组中删除第一个元素,并返回删除的元素
        public E removeFirst() {
            return remove(0);
        }
        //从数组中删除元素e
        public void removeElement(E e) {
            int index = find(e);
            if (index != -1){
                remove(index);
            }
        }
        @Override
        public String toString() {
            StringBuilder res = new StringBuilder();
            res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
            res.append("[");
            for (int i = 0; i < size; i++) {
                res.append(data[i]);
                if (i != size - 1) {
                    res.append(", ");
                }
            }
            res.append("]");
            return res.toString();
        }
    }

然后我们进行一下测试

    public static void main(String[] args) {
        Array<String> arr = new Array<>(10);
        arr.addLast("张三");
        arr.addLast("李四");
        arr.addLast("王五");
        System.out.println(arr);
    }
Array: size = 3 , capacity = 10[张三, 李四, 王五]

这样我们就可以很轻易的实现了不同对象的数组。

动态数组

现在我们的数组还是一个有限的固定的容量,如果预估容量过大,会导致浪费很多空间,如果预估容量过小,则会出现不够用,所以我们需要使用可伸缩的动态数组。

如果当前数组已经满了,那我们就开辟一个新的数组,然后将data的数组进行循环拷贝过去,然后将data指向新的数组。

public void add(int index, E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("add failed. Require index >= 0 and index <= size.");
        }
        //如果数组已经满了,则扩容一倍
        if (size == data.length) {
            resize(2 * data.length);
        }
        //将大于index的元素都进行索引加一
        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        data[index] = e;
        size++;
    }
    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i]= data[i];
        }
        data = newData;
}

相应的,如果数组缩减到一定程度,我们也要将数组进行缩容。

    //从数组中删除index位置的元素,并返回删除的元素
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("remove failed. Require index >= 0 and index < size.");
        }
        E ret = data[index];
        for (int i = index + 1; i < size; i++) {
            data[i - 1] = data[i];
        }
        size --;
        //回收当前无用的数据
        data[size] = null;
        //缩容
        if (size == data.length / 2 && data.length / 2 != 0){
            resize(data.length / 2);
        }
        return ret;
    }

简单时间复杂度分析

  • 添加操作

    • addLast(e)    O(1)
    • addFirst(e) O(n)
    • add(index,e)   O(n/2) = O(n)
  • 删除操作

    • removeLast(e)   O(1)
    • removeFirst(e) O(n)
    • remove(index,e)  O(n/2) = O(n)
  • 修改操作

    • set(index,e) O(1)
  • 查找操作

    • get(index) O(1)
    • contains(e)   O(n)
    • find(e)   O(n)

神秘杰克
768 声望392 粉丝

Be a good developer.