# 查看数组的大小

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/22408.html | 发布：2023-07-25 | 更新：2023-07-25 | 分类：建站教程

查看数组大小：

 

成功扩容为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)

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
