数据结构day1(Java二次封装原有数组,实现“可变数组”)

数据结构day1(Java二次封装原有数组,实现“可变数组”)

数组作为一种常见的数据类型想必大家都能熟练的掌握并使用,想必大家对Java中数组长度不可变的特性又爱又恨。本篇博文将对Java原有的数组进行再次封装,实现我们自己的可变数组,并实现对数组元素的增,删,改,查等方法。

废话不多说,自制数组类如下:

package com.ljt.datastructure.array;

public class MyArray<T> {

    T[] data;   //存放数据的容器,用泛型数组实现
    int size;   //实际存放元素的个数

    //构造函数
    public MyArray(int capacity){
        data = (T[])new Object[capacity];   //参数为为容器的总容量
        size = 0;
    }

    public MyArray(){
        this(10);   //无参构造方法,默认容量为10
    }

    //判断数组是否为空
    public boolean isEmpty(){
        return this.size == 0;
    }

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

    //在数组指定位置添加元素
    public void addElement(int index,T element) throws Exception {
        if(index < 0 || index > size){
            throw new Exception("Index is invalid");
        }
        if(size == this.getCapacity()){
            throw new Exception("MyArray already IndexOutOfBounds");
        }
        for(int i = size-1;i>=index;i--){
            data[i+1] = data[i];
        }
        data[index] = element;
        size++;
    }

    //在数组末尾添加元素
    public void addElementAtLast(T element) throws Exception {
        this.addElement(size,element);
    }

    //在数组首位添加元素
    public void addElementAtFirst(T element) throws Exception {
        this.addElement(0,element);
    }

    //获取指定位置的元素
    public T getElementfByIndex(int index) throws Exception {
        if(index < 0 || index >= size){
            throw new Exception("Index is invalid");
        }
        return data[index];
    }

    //获取指定元素的位置
    public int getIndexByElement(T element){
        int index = -1;
        for(int i = 0;i<size;i++){
            if(data[i].equals(element)){
                index = i;
                break;
            }
        }
        return index;
    }

    //修改指定位置的元素
    public void setElementByIndex(int index,T element) throws Exception {
        if (index < 0 || index >= size) {
            throw new Exception("Index is invalid!");
        }
        data[index] = element;
    }

    //判断数组中是否包含指定元素
    public boolean isContains(T element){
        boolean flag = false;
        for (T item:data) {
            if(item == element){
                flag = true;
                break;
            }
        }
        return flag;
    }

    //删除指定位置的元素
    public void delateElementByIndex(int index) throws Exception {
        if(index < 0 || index >= size){
            throw new Exception("Index is invalid");
        }
        for(int i = index;i<size-1;i++){
            data[i] = data[i+1];
        }
        data[size-1] = null;
        size--;
    }

    //删除指定元素
    public void delateElementByValue(T element) throws Exception {
        int index = getIndexByElement(element);
        if(index == -1){
            throw new Exception("Element Not Found!");
        }else{
            delateElementByIndex(index);
        }
    }

    //重写Object类中的toString,返回该对象的字符串表示。(在System.out.println()时自动调用)
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("容量:"+getCapacity()+","+"实际存放元素个数为:"+size+"\n");
        sb.append("[");
        for(int i=0;i<size;i++){
            sb.append(data[i]);
            if(i != size-1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

注:代码注释中的数组指的是自定义容器类的实例而不是Java中的数组。

写个测试类对自制数组进行测试:

public class Main {
    public static void main(String[] args) throws Exception {
        //创建一个容量大小为20的MyArray<Integer>的数组
        MyArray<Integer> myArr = new MyArray<Integer>(20);

        //调用isEmpty()判断数组是否为空
        System.out.println(myArr.isEmpty());    //还未向数组中添加元素,返回true
        System.out.println(myArr.getCapacity());    //返回数组的容量,即创建对象时传入的参数20

        for (int i = 0; i < 5; i++) {
            myArr.addElementAtLast(10); //调用addElementAtLast()方法,为数组中添加5个值为10的元素
        }

        System.out.println(myArr.isEmpty());    //向数组中添加了元素,返回false
        System.out.println(myArr);  //打印该数组对象 [10,10,10,10,10]

        myArr.addElement(2, 2);  //在下标为2的位置插入值为2的元素 [10,10,2,10,10,10]
        myArr.addElementAtLast(5);  //在数组末尾添加一个值为5的元素 [10,10,2,10,10,10,5]
        myArr.addElementAtFirst(0); //在数组首位添加一个值为0的元素 [0,10,10,2,10,10,10,5]

        System.out.println(myArr.getElementfByIndex(3));    //打印数组下标为3的元素 2
        System.out.println(myArr.getIndexByElement(2));     //打印值为2的元素的下标 3

        myArr.setElementByIndex(4, 4);   //将数组下标为4的元素的值改为4 [0,10,10,2,4,10,10,5]
        System.out.println(myArr.isContains(5));    //判断数组中是否有值为5的元素 true

        myArr.delateElementByIndex(6);  //删除下标为6的元素 [0,10,10,2,4,10,5]
        myArr.delateElementByValue(10); //删除值为10的元素 [0,10,2,4,10,5]
        /*
         * 当数组中有多个指定元素时,delateElementByValue()方法一次只能删除排在最前面的那个指定元素
         * 若是想要删除所有的指定元素,可以使用循环访问每个数组元素,对每个元素的值与指定值判断,如果等于指定值,就调用delateElementByValue()方法
         * 代码:
        int count = 0;
        for (int i = 0; i < myArr.size; i++) {
            if (myArr.getElementfByIndex(i) == 10) {
                count++;
            }
        }
        int index = 0;
        while(count>0){
            if(myArr.getElementfByIndex(index) == 10){
                myArr.delateElementByValue(10);
                count--;
            }
            index++;
        }
         */

        System.out.println(myArr);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值