算法 玩转数据结构 2-4 数组中查询元素和修改元素

0    课程来源

https://coding.imooc.com/lesson/207.html#mid=13409

 

1    重点关注

1.1    toString方法范式

参考coding

 

1.2    coding

 

2    课程内容

coding

 

3    Coding

3.1    coding看4

package com.company;

import java.util.Arrays;

public class Array {
    private int size;
    //int类型的数组
    private int[] data;


    //1.1  创建构造函数,传入容量,则新生成一个数组
    public Array(int capacity){
        data = new int[capacity];
        size = 0;
    }

    //1.2  创建无参构造函数
    public Array(){
        this(10);
    }

    //1.3  添加传入静态数组的构造函数
    public Array(int[] param){
        this.data = param;
        long outParm = Arrays.stream(param).filter(e->{
            return e>0;
        }).count();
        this.size = (int)outParm;
    }

    //2.1  添加getSize,获取数组元素个数
    public int getSize(){
        return size;
    }

    //2.2  添加getCapacity,获取数组容量
    public int getCapacity(){
        return data.length;
    }

    //2.3  添加数组是否为空方法
    public boolean isEmpty(){
        return size==0;
    }

    //3.1  在数组末尾添加元素
    public void addLast(int e){
        addElement(size,e);
    }

    //3.2  在数组起始添加元素
    public void addFirst(int e){
        addElement(0,e);
    }

    //3.3  数组根据索引添加元素
    public void addElement(int index,int e){
        //1     校验异常
        //1.1   如果数组已经满了,则禁止插入
        if(size== data.length){
            throw new IllegalArgumentException("数组已满,禁止插入");
        }

        //1.2   如果传入的索引在已有数组的索引之外,则校验异常
        if(index<0||index>size){
            throw new IllegalArgumentException("索引应在已有数组的索引之间");
        }

        //2     实现根据索引添加元素的逻辑
        //2.1   data同步
        for(int j = size-1;j>=index;j--){
            data[j+1] = data[j];
        }
        data[index] = e;

        //2.2   size同步
        size++;
    }

    //4.1     数组 toString 范例
    @Override
    public String toString() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(String.format("Array:size = %d,capacity = %d\n",size,data.length));

        stringBuffer.append("[");
        for(int i=0;i<size;i++){
            stringBuffer.append(data[i]);
            if(i!=size-1){
                stringBuffer.append(",");
            }
        }
        stringBuffer.append("]");
        return stringBuffer.toString();
    }

    //4.2     get获取元素
    public int get(int index){
        if(index<0||index>data.length){
            throw new IllegalArgumentException("111");
        }
        return data[index];
    }

    //4.3       set获取元素
    public void set(int index,int e){
        if(index<0||index>data.length){
            throw new IllegalArgumentException("111");
        }
        data[index] = e;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章