查看数组的大小

查看数组大小

成功扩容为20大小的数组。

实现获取pos位置元素和顺序表的长度,以及设置元素这三个接口。由于获取和设置元素都需要检查下标是否合法。所以我们写一个判断位置是否合法的方法。我们在判断非法的时候我们直接输出非法不合适,我们应该建立一个异常,然后抛出异常.

建立异常:

public class PosOutBoundsException extends RuntimeException{
    public PosOutBoundsException() {
    }
    public PosOutBoundsException(String message) {
        super(message);
    }
}

接口的实现:

// 获取 pos 位置的元素
public int get(int pos)  {
    if (!checkPos(pos)){
        throw new RuntimeException("get 元素位置错误");
    }
    return this.elem[pos];
}
// 获取顺序表长度
public int size() {
    return this.usedSize;
}
// 给 pos 位置的元素设为 value【更新的意思 】
public void set(int pos, int value) {
    if (!checkPos(pos)){
        throw new RuntimeException("set 元素位置错误");
    }
    this.elem[pos] = value;
}
//检查pos下表是否 合法
private boolean checkPos(int pos){
    if (pos < 0 || pos >= this.usedSize) return false;
    return true;
}

进行新增数据的测试 :

public static void main(String[] args) {
    SeqList seqList = new SeqList();
    seqList.add(1);
    seqList.add(2);
    seqList.add(3);
    seqList.add(4);
    seqList.add(5);
    seqList.add(6);
    System.out.println(seqList.get(3));
    seqList.display();
    seqList.set(3,1000);
    seqList.display();
    seqList.get(10);//获取元素位置错误抛出异常。
}

最后输出结果:

    4
    1 2 3 4 5 6
    1 2 3 1000 5 6
    Exception in thread “main” java.lang.RuntimeException: get 元素位置错误
    at demoList2.SeqList.get(SeqList.java:56)
    at demoList2.Test.main(Test.java:17)

文章链接: https://www.mfisp.com/22408.html

文章标题:查看数组的大小

文章版权:梦飞科技所发布的内容,部分为原创文章,转载请注明来源,网络转载文章如有侵权请联系我们!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
建站教程

数据结构顺序表

2023-7-25 13:23:39

建站教程

ArrayList的构造

2023-7-26 14:26:03

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
客户经理
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索

梦飞科技 - 最新云主机促销服务器租用优惠