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

    }
}
相关推荐
艾莉丝努力练剑11 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
武子康1 小时前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
椰椰椰耶3 小时前
【Spring】拦截器详解
java·后端·spring
没有bug.的程序员4 小时前
JAVA面试宝典 - 《MyBatis 进阶:插件开发与二级缓存》
java·面试·mybatis
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian5 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
没有羊的王K5 小时前
SSM框架学习——day1
java·学习
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
又菜又爱coding5 小时前
安装Keycloak并启动服务(macOS)
java·keycloak