模拟实现ArrayList类

本篇学习如何模拟实现ArrayList类

结构

1、异常

定义两个异常,顺序表为空异常及数组下表不合法

顺序表为空异常

public class EmptyException extends RuntimeException{
    public EmptyException() {
        super();
    }

    public EmptyException(String message) {
        super(message);
    }
}

数组下表不合法

public class PosIllegal extends RuntimeException{
    public PosIllegal(){

    }

    public PosIllegal(String message) {
        super(message);
    }
}

2、MyArrayList类

共包含增删改查等方法。代码有注释

public class MyArrayList {
    public int[] elem;
    public int usedSize;//0
    //默认容量
    private static final int DEFAULT_SIZE = 10;

    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    /**
     * 打印顺序表:
     *   根据usedSize判断即可
     */
    public void display() {
        for (int i = 0; i <usedSize ; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println("");
    }

    // 新增元素,默认在数组最后新增
    public void add(int data) {
        if(isFull()){
            grow();
        }
     this.elem[this.usedSize++]=data;
    }

    /**
     * 判断当前的顺序表是不是满的!
     * @return true:满   false代表空
     */
    public boolean isFull() {
        return this.usedSize==elem.length;
    }

    //检查pos位置是否合法,用于add方法
    private boolean checkPosInAdd(int pos) throws PosIllegal{
        if(pos<0||pos>usedSize) {
            throw new PosIllegal("pos位置不合法");
            //合法
        }
        return false;
    }
    //检查pos位置是否合法,用于删,改,查
    private boolean checkPos(int pos) throws PosIllegal{
        if(pos<0||pos>=usedSize) {
            throw new PosIllegal("pos位置不合法");
            //合法
        }
        return false;
    }

    // 在 pos 位置新增元素
    public void add(int pos, int data) {
      try {
          checkPosInAdd(pos);
          if(isFull())
              grow();

          for (int i =usedSize-1 ; i>=pos ; i--) {
              elem[i+1]=elem[i];
          }
          elem[pos]=data;
         usedSize++;
      }catch(PosIllegal e){
            e.printStackTrace();
          System.out.println("插入元素pos位置不合法");
        }
      }

      //扩容
    private void grow(){
        this.elem=Arrays.copyOf(this.elem,2*this.elem.length);
  }

    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind)
                return true;
        }
       return false;
    }
    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind)
                return i;
        }
        return -1;
    }

    // 获取 pos 位置的元素
    public int get(int pos) {
        try{
            checkEmpty();
            checkPos(pos);
            return elem[pos];
        }catch(PosIllegal e){
            e.printStackTrace();
            System.out.println("pos位置不合法");
        }catch(EmptyException e){
            e.printStackTrace();
            System.out.println("pos位置为空");
        }
        return -1;
    }

    //判断是否为空,抛出异常
    private void checkEmpty(){
        if(isEmpty())
            throw new EmptyException("顺序表为空");
    }
    //判断是否为空
    private boolean isEmpty() {
        return usedSize==0;
    }
    // 给 pos 位置的元素设为【更新为】 value
    public void set(int pos, int value) {
        try{
            checkEmpty();
            checkPos(pos);
            elem[pos]=value;
        }catch(PosIllegal e){
            e.printStackTrace();
            System.out.println("pos位置不合法");
        }catch(EmptyException e){
            e.printStackTrace();
            System.out.println("pos位置为空");
        }
    }

    /**
     * 删除第一次出现的关键字key
     * @param key
     */
    public void remove(int key) {
       try{
           checkEmpty();
           int pos = indexOf(key);
           for (int i = pos; i < usedSize-1; i++) {
               elem[i]=elem[i+1];
           }
           usedSize--;
       }catch (EmptyException e){
           e.printStackTrace();
       }
    }

    // 获取顺序表长度
    public int size() {
        return usedSize;
    }

    // 清空顺序表
    public void clear() {
          usedSize=0;
    }

}

3、测试类

public class Test {
    public static void main(String[] args) {
        MyArrayList myArrayList=new MyArrayList();
        myArrayList.add(5);
        myArrayList.add(1);
        myArrayList.add(3);
        myArrayList.add(7);
        myArrayList.add(0);
       
        //打印数字为4的下标
        int ret= myArrayList.indexOf(4);
        System.out.println(ret);

         //移除数字3
        myArrayList.remove(3);
        //设置数组下标4的位置为1
        myArrayList.set(4,1);
        //打印数组
        myArrayList.display();

    }
}
相关推荐
c4fx5 分钟前
Delphi5利用DLL实现窗体的重用
开发语言·delphi·dll
kinlon.liu12 分钟前
零信任安全架构--持续验证
java·安全·安全架构·mfa·持续验证
鸽芷咕28 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
王哲晓33 分钟前
Linux通过yum安装Docker
java·linux·docker
Jhxbdks38 分钟前
C语言中的一些小知识(二)
c语言·开发语言·笔记
java66666888838 分钟前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存38 分钟前
源码分析:LinkedList
java·开发语言
执键行天涯39 分钟前
【经验帖】JAVA中同方法,两次调用Mybatis,一次更新,一次查询,同一事务,第一次修改对第二次的可见性如何
java·数据库·mybatis
代码雕刻家40 分钟前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
Fan_web42 分钟前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html