模拟实现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();

    }
}
相关推荐
mark-puls9 小时前
C语言打印爱心
c语言·开发语言·算法
mkhase9 小时前
9.12-QT-基本登陆界面实现
java·jvm·qt
yinke小琪9 小时前
说说hashCode() 和 equals() 之间的关系
java·后端·面试
若鱼19199 小时前
Kafka如何配置生产者拦截器和消费者拦截器
java·kafka
西阳未落9 小时前
C语言柔性数组详解与应用
c语言·开发语言·柔性数组
Huhbbjs9 小时前
SQL 核心概念与实践总结
开发语言·数据库·sql
渣哥9 小时前
Java 自适应自旋锁机制详解:原理、优缺点与应用场景
java
咕噜咕噜啦啦9 小时前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
摇滚侠9 小时前
java语言中,list<String>转成字符串,逗号分割;List<Integer>转字符串,逗号分割
java·windows·list
Source.Liu9 小时前
【Pywinauto库】12.1 pywinauto.backend 后端内部实施模块
开发语言·windows·python·自动化