work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

自定义数组(动态数组)

Posted on 2021-02-07 09:26  work hard work smart  阅读(303)  评论(0编辑  收藏  举报

数组的定义,参考Java 数组

数组的使用

1、定义一个数组

        //必须初始化数组的长度,这里为10
        int[] arr = new int[10];
        for(int i = 0;i < arr.length; i++){
            arr[i] = i;
        }

        //设置初始值
        int[] score = new int [] {10,20,30};

  

 2、自定义数组

public class CustomArray<E> {

    private  E[] data;
    //数组长度
    private int size;

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

    /**
     * 无参数的构造函数
     */
    public CustomArray(){
        this(10);
    }

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

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

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

    //向所有元素添加一个新元素
    public  void addLast(E e){
        /*if(size == data.length){
            throw new IllegalArgumentException("addLast fail, Array is already full");
        }
        data[size] = e;
        size ++;*/
        add(size, e);
    }

    //向所有元素添加一个新元素
    public void addFirst(E e){
        add(0, e);
    }


    //向第index个元素中插入一个新元素e
    public  void add(int index, E e){

        if(index < 0 || index > size){
            throw new IllegalArgumentException("addLast fail,require index < 0 || index > size");
        }

        //动态数组
        if(size == data.length){
            //throw new IllegalArgumentException("addLast fail, Array is already full");
            // 扩容到原来数组长度的两倍
            resize(2 * data.length);
        }

        for(int i = size -1; i>= index; i--){
            //将i元素值往后移动1位
            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索引位置的元素
    E get(int index){
        if(index < 0 || index >= size){
            throw new IllegalArgumentException("get fail,require index < 0 || index >= size");
        }
        return  data[index];
    }

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

    //查找数组中是否有元素e
    public boolean contains(E e){
        for(int i = 0; i < size; i++){
            if(data[i].equals(e)){
                return  true;
            }
        }
        return  false;
    }

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

    //从数组中删除index位置的元素,返回删除的元素
    public  E remove(int index){
        if(index < 0 || index >= size){
            throw new IllegalArgumentException("set fail,require index < 0 || index >= size");
        }
        E ret = data[index];
        for(int i = index +1; i < size; i++){
            data[i-1] = data[i];
        }
        size--;
        //loitering objects != memory leak 这句话不是不必须的
        data[size] = null;
        //数据只有容量的1/4的时候
        if(size <= data.length / 4 && data.length / 2 != 0){
            //缩小容量为当前容量的一半
            resize(data.length / 2);
        }
        return  ret;
    }

    //从数组中删除第一个位置的元素,返回删除的元素
    public  E removeFirst(){
        return remove(0);
    }

    //从数组中删除最后一个位置的元素,返回删除的元素
    public  E removeLast(){
        return remove(size - 1);
    }

    //从数组中删除元素e
    public void removeElement(E e){
        int index = find(e);
        if(index != -1){
            remove(index);
        }
    }


    @Override
    public  String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("Array size= %d, capacity = %d  ", this.size, data.length));
        sb.append("'[");
        for(int i = 0; i< size; i++){
            sb.append(data[i]);
            if(i != size -1){
                sb.append(", ");
            }
        }
        sb.append("]'");
        return  sb.toString();
    }


}

  

自定义数组测试:

public static void main(String[] args) {
        CustomArray<Integer> arr = new CustomArray(20);
        for(int i = 0; i < 10; i++){
            arr.addLast(i);
        }
        System.out.println(arr); //输出:  Array size= 10, capacity = 20  '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'

        arr.add(1, 100);
        System.out.println(arr); // 输出:  Array size= 11, capacity = 20  '[0, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9]'

        arr.addFirst(200);
        System.out.println(arr); // 输出:Array size= 12, capacity = 20  '[200, 0, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9]'

        //删除索引为2的元素
        arr.remove(2);
        System.out.println(arr); //输出: Array size= 11, capacity = 20  '[200, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'

        //删除元素6
        arr.removeElement(6);
        System.out.println(arr); // 输出: Array size= 10, capacity = 20  '[200, 0, 1, 2, 3, 4, 5, 7, 8, 9]'

        //移除第一个元素
        arr.removeFirst();
        System.out.println(arr); // 输出: Array size= 9, capacity = 20  '[0, 1, 2, 3, 4, 5, 7, 8, 9]'
    }

 

增加容量测试:

  /**
     * 增加容量测试
     */
    private void addCapacityTest(){
        //动态数组测试。容量为10
        CustomArray<Integer> arr = new CustomArray(10);
        for(int i = 0; i < 10; i++){
            arr.addLast(i);
        }
        System.out.println(arr); //Array size= 10, capacity = 10  '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'

        //新增一个数字,自动进行扩容
        arr.add(1, 100);
        System.out.println(arr); // 输出: Array size= 11, capacity = 20  '[0, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
    }


    /**
     * 较少容量测试
     */
    private void reduceCapacity(){
        //动态数组测试。容量为10
        CustomArray<Integer> arr = new CustomArray(20);
        for(int i = 0; i < 10; i++){
            arr.addLast(i);
        }
        System.out.println(arr); //Array size= 10, capacity = 10  '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'


        arr.remove(2);
        System.out.println(arr); // 输出: Array size= 9, capacity = 10  '[0, 1, 3, 4, 5, 6, 7, 8, 9]'
    }

  

 

 

使用类型为Student测试

public class Student {
    private String name;
    private int score;

    public Student(String name, int score){
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    public static void main(String[] args) {
        CustomArray<Student> arr = new CustomArray<Student>();
        arr.addLast(new Student("zhangsan",50));
        arr.addLast(new Student("lisi",60));
        arr.addLast(new Student("wangwu",55));
        System.out.println(arr); //输出: Array size= 3, capacity = 10  '[Student{name='zhangsan', score=50}, Student{name='lisi', score=60}, Student{name='wangwu', score=55}]'

    }
}