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

    }
}
相关推荐
lzb_kkk11 分钟前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
YuTaoShao23 分钟前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
好开心啊没烦恼31 分钟前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
Dcs1 小时前
超强推理不止“大”——手把手教你部署 Mistral Small 3.2 24B 大模型
java
简佐义的博客1 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
东阳马生架构1 小时前
订单初版—1.分布式订单系统的简要设计文档
java
程序员爱钓鱼1 小时前
【无标题】Go语言中的反射机制 — 元编程技巧与注意事项
开发语言·qt
Frank学习路上1 小时前
【IOS】XCode创建firstapp并运行(成为IOS开发者)
开发语言·学习·ios·cocoa·xcode
Code blocks1 小时前
使用Jenkins完成springboot项目快速更新
java·运维·spring boot·后端·jenkins