手写数组的底层实现(java实现)

打造属于自己的Array

​ 查看JDK1.8中ArrayList源码时,其中的Arrays.copyOf为Native方法,具体怎么实现的并没有。所以打算自己实现,来深入了解一下Array这个数据结构。

静态数组

创建增删改查方法

在这里插入图片描述

  1. 自己创建数组无非就是数组的 增删改查 方法的创建,即 add,remove,set,get 方法。

  2. 首先创建一个简单的int集合来表示数组,默认大小为10,添加一些常规的方法之后,再对重要的方法进行单独书写

  3. add方法:在指定索引位置插入数字,就相当于把指定索引处后的值往后移一位,即把值赋给下一个索引,一层for循环就可以,同时不要忘记size++,然后再在指定索引处赋值。

  4. remove方法:在指定索引位置删除数字,就相当于把指定索引处后的值往前移一位,即把值赋给上一个索引,一层for循环就可以,同时不要忘记size–。这里有所不同,即int[size]的值需不需要删除,其实这里删不删除并不影响数组的逻辑和功能实现,但本着严谨的态度,将int[size]赋值为null,节省一点内存空间。

    package design.Array;
    
    /**
     * @program: design
     * @description: Array类
     * @author: cyj
     * @create: 2019-03-18 21:23
     **/
    public class Array {
        private int[] data;
        private int size;
    
        /**
         * 构造函数,传入数组的容量capacity构造Array
         *
         * @param capacity
         */
        public Array(int capacity) {
            data = new int[capacity];
            size = 0;
        }
    
        /**
         * 无参数的构造函数,默认数组的容量capacity=10
         */
        public Array() {
            this(10);
        }
    
        /**
         * 获取数组中的元素个数
         *
         * @return
         */
        public int getSize() {
            return size;
        }
    
        /**
         * 获取数组的容量
         *
         * @return
         */
        public int getCapacity() {
            return data.length;
        }
    
        /**
         * 返回数组是否为空
         *
         * @return
         */
        public boolean isEmpty() {
            return size == 0;
        }
    
        /**
         * 向所有元素后添加一个新元素e
         *
         * @param e
         */
        public void addLast(int e) {
    //        if (size == data.length) {
    //            throw new IllegalArgumentException("AddLast failed.Array is full.");
    //        }
    //        data[size] = e;
    //        size++;
            add(size, e);
        }
    
        /**
         * 向所有元素前添加一个新元素e
         *
         * @param e
         */
        public void addFirst(int e) {
            add(0, e);
        }
    
        /**
         * 在第index个位置插入一个新元素e
         *
         * @param index
         * @param e
         */
        public void add(int index, int e) {
            if (size == data.length) {
                throw new IllegalArgumentException("Add failed.Array is full.");
            }
            if (index < 0 || index > size) {
                throw new IllegalArgumentException("Add failed.Require index >=0 is full.");
            }
            for (int i = size - 1; i >= index; i--) {
                data[i + 1] = data[i];
            }
            data[index] = e;
            size++;
        }
    
        /**
         * 获取index索引位置的元素
         *
         * @param index
         * @return
         */
        int get(int index) {
            if (index < 0 || index > size) {
                throw new IllegalArgumentException("Get failed.Require index is illegal.");
            }
            return data[index];
        }
    
        /**
         * 修改index索引位置的元素为e
         *
         * @param index
         * @param e
         */
        void set(int index, int e) {
            if (index < 0 || index > size) {
                throw new IllegalArgumentException("Set failed.Require index is illegal.");
            }
            data[index] = e;
        }
    
        /**
         * 查找数据中是否有元素e
         *
         * @param e
         * @return
         */
        public boolean contains(int e) {
            for (int i = 0; i < size; i++) {
                if (data[i] == e) {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 查找数组中元素e所在的索引,如果不存在则返回索引为-1
         *
         * @param e
         * @return
         */
        public int find(int e) {
            for (int i = 0; i < size; i++) {
                if (data[i] == e) {
                    return i;
                }
            }
            return -1;
        }
    
        /**
         * 从数组中删除index位置的元素,返回删除的元素
         *
         * @param index
         * @return
         */
        public int remove(int index) {
            if (index < 0 || index > size) {
                throw new IllegalArgumentException("Remove failed.Require index is illegal.");
            }
            int ret = data[index];
            for (int i = index + 1; i < size; i++) {
                data[i - 1] = data[i];
            }
            size--;
            return ret;
        }
    
        /**
         * 从数组中删除index位置的元素,返回删除的元素
         *
         * @return
         */
        public int removeFirst() {
            return remove(0);
        }
    
        /**
         * 从数组中删除index位置的元素,返回删除的元素
         *
         * @return
         */
        public int removeLast() {
            return remove(size - 1);
        }
    
        /**
         * 从数组中删除元素e
         * 1. 可以返回boolean  2.重复数组的考量,删除所有的元素e,设计上的考虑,具体需求具体分析
         *
         * @param e
         */
        public void removeElement(int 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();
        }
    }
    

测试静态数组类

package design.Array;

/**
 * @program: design
 * @description: 测试Array类
 * @author: cyj
 * @create: 2019-03-19 10:02
 **/
public class ArrayTest {
    public static void main(String[] args) {
        Array arr = new Array(20);
        for (int i = 0; i < 10; i++) {
            arr.addLast(i);
        }
        System.out.println(arr);

        arr.add(1, 100);
        System.out.println(arr);

        arr.addFirst(-1);
        //[-1,0,100,1,2,3,4,5,6,7,8,9]
        System.out.println(arr);

        arr.remove(2);
        //[-1,0,1,2,3,4,5,6,7,8,9]
        System.out.println(arr);

        arr.removeElement(4);
        //[-1,0,1,2,3,5,6,7,8,9]
        System.out.println(arr);

        arr.removeFirst();
        //[0, 1, 2, 3, 5, 6, 7, 8, 9]
        System.out.println(arr);
    }
}

输出结果(重写类的toString方法):
Array: size=10 , capacity=20
[0,1,2,3,4,5,6,7,8,9]

Array: size=11 , capacity=20
[0,100,1,2,3,4,5,6,7,8,9]

Array: size=12 , capacity=20
[-1,0,100,1,2,3,4,5,6,7,8,9]

Array: size=11 , capacity=20
[-1,0,1,2,3,4,5,6,7,8,9]

Array: size=10 , capacity=20
[-1,0,1,2,3,5,6,7,8,9]

Array: size=9 , capacity=20
[0,1,2,3,5,6,7,8,9]

泛型和动态数组的实现

泛型

在实际运用中,我们不能只是简单的用整数型数组来表示,这里就要引出泛型的概念。

  • 泛型,即“参数化类型”。一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?

    顾名思义,就是将类型由原来的具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),然后在使用/调用时传入具体的类型(类型实参)。

    泛型的本质是为了参数化类型(在不创建新的类型的情况下,通过泛型指定的不同类型来控制形参具体限制的类型)。也就是说在泛型使用过程中,操作的数据类型被指定为一个参数,这种参数类型可以用在类、接口和方法中,分别被称为泛型类、泛型接口、泛型方法。

  • 因为不能直接定义泛型,所以可以通过定义Object的方式来强转为泛型

  • 定义了泛型之后就可以接收的多种类型,因为泛型把具体的参数类型泛化,模糊化,使得传参可以有更多种的选择。

动态数组

动态数组的实现即实现了数组的扩容。扩容的过程是

  • 是否超出了默认的数组长度,超出则执行扩容方法

  • 扩容是新建一个数组,新建数组的长度为原数组的2倍(ArrayList为1.5倍,通过位运算来计算),接着把原数组的值通过for循环来赋值到新数组,在接着把原数组的引用指向新数组。

  • 在增加和删除的时候进行扩容和缩容(新建一个为原数组长度1/2的新数组)

  • 在数组缩容的问题上,为了防止复杂度的震荡,数组在长度边缘疯狂的试探,频繁的进行扩容和缩容。(即数组长度为10,增加一个元素扩大为20,之后紧接着又删除一个元素,又缩容为10)。

    所以缩容的时候判断数组实际长度为1/4时才进行缩容,就可以减少疯狂的试探,从而防止方法的时间复杂度一直为O(n)。

package design.Array;

/**
 * @program: design
 * @description: Array类
 * @author: cyj
 * @create: 2019-03-18 21:23
 **/
public class ArrayObject<E> {
    private E[] data;
    private int size;

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

    /**
     * 无参数的构造函数,默认数组的容量capacity=10
     */
    public ArrayObject() {
        this(10);
    }

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

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

    /**
     * 返回数组是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 向所有元素后添加一个新元素e
     * 时间复杂度:O(1)
     *
     * @param e
     */
    public void addLast(E e) {
//        if (size == data.length) {
//            throw new IllegalArgumentException("AddLast failed.Array is full.");
//        }
//        data[size] = e;
//        size++;
        add(size, e);
    }

    /**
     * 向所有元素前添加一个新元素e
     * 时间复杂度:O(n)
     *
     * @param e
     */
    public void addFirst(E e) {
        add(0, e);
    }

    /**
     * 在第index个位置插入一个新元素e
     * 时间复杂度:O(n/2)=>O(n)
     *
     * @param index
     * @param e
     */
    public void add(int index, E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("Add failed.Require index >=0 is full.");
        }
        if (size == data.length) {
            resize(2 * data.length);
        }
        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        data[index] = e;
        size++;
    }

    /**
     * 获取index索引位置的元素
     * 时间复杂度:O(1)
     *
     * @param index
     * @return
     */
    public E get(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("Get failed.Require index is illegal.");
        }
        return data[index];
    }

    /**
     * 修改index索引位置的元素为e
     * 时间复杂度:O(1)
     *
     * @param index
     * @param e
     */
    public void set(int index, E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("Set failed.Require index is illegal.");
        }
        data[index] = e;
    }

    /**
     * 查找数据中是否有元素e
     * 时间复杂度:O(n)
     *
     * @param e
     * @return
     */
    public boolean contains(E e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查找数组中元素e所在的索引,如果不存在则返回索引为-1
     * 时间复杂度:O(n)
     *
     * @param e
     * @return
     */
    public int find(E e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 从数组中删除index位置的元素,返回删除的元素
     * 时间复杂度:O(n/2)=>O(n)
     *
     * @param index
     * @return
     */
    public E remove(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("Remove failed.Require index is illegal.");
        }
        E ret = data[index];
        for (int i = index + 1; i < size; i++) {
            data[i - 1] = data[i];
        }
        size--;
        //loireting objects !=memory leak,不写的话逻辑上也正确
        data[size] = null;
        //防止复杂度震荡,所以1/4  防止删到最后一位
        if (size == data.length / 4 && data.length / 2 != 0) {
            resize(data.length / 2);
        }
        return ret;
    }

    /**
     * 从数组中删除index位置的元素,返回删除的元素
     * 时间复杂度:O(n)
     *
     * @return
     */
    public E removeFirst() {
        return remove(0);
    }

    /**
     * 从数组中删除index位置的元素,返回删除的元素
     * 时间复杂度:O(1)
     *
     * @return
     */
    public E removeLast() {
        return remove(size - 1);
    }

    /**
     * 从数组中删除元素e
     * 1. 可以返回boolean  2.重复数组的考量,删除所有的元素e,设计上的考虑,具体需求具体分析
     *
     * @param 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();
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }
        data = newData;
    }
}

测试动态数组类

泛型测试类
package design.Array;

/**
 * @program: design
 * @description: 测试泛型类数组实体类
 * @author: cyj
 * @create: 2019-03-19 11:44
 **/
public class Test {
    private String name;
    private String age;

    public Test(String name, String age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return String.format("Student(name: %s, age: %s)", name, age);
    }

    public static void main(String[] args) {
        ArrayObject<Test> arrayObject = new ArrayObject<>();
        arrayObject.addLast(new Test("sangsan", "21"));
        arrayObject.addLast(new Test("lisi", "22"));
        arrayObject.addLast(new Test("wangwu", "23"));
        System.out.println(arrayObject);
    }
}

输出结果:
Array: size=3 , capacity=10
[Student(name: sangsan, age: 21), Student(name: lisi, age: 22), Student(name: wangwu, age: 23)]
动态数组测试类
package design.Array;

/**
 * @program: design
 * @description: 测试ArrayObject类
 * @author: cyj
 * @create: 2019-03-19 10:02
 **/
public class ArrayTestObject {
    public static void main(String[] args) {
        ArrayObject<Integer> arr = new ArrayObject<>();
        for (int i = 0; i < 10; i++) {
            arr.addLast(i);
        }
        System.out.println(arr);

        arr.add(1, 100);
        System.out.println(arr);

        arr.addFirst(-1);
        System.out.println(arr);

        arr.remove(2);
        System.out.println(arr);

        arr.removeElement(4);
        System.out.println(arr);

        arr.removeFirst();
        System.out.println(arr);
    }
}

输出结果(可以看出来数组的长度在变化了):
Array: size=10 , capacity=10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array: size=11 , capacity=20
[0, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array: size=12 , capacity=20
[-1, 0, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array: size=11 , capacity=20
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array: size=10 , capacity=20
[-1, 0, 1, 2, 3, 5, 6, 7, 8, 9]
Array: size=9 , capacity=20
[0, 1, 2, 3, 5, 6, 7, 8, 9]
数组的底层实现就先写到这里,可以看出效果还是可以的,之后会继续基于数组来实现栈,队列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值