如何调用自定义Java数组

如何调用自定义Java数组,java,arrays,Java,Arrays,当我试图编译这段代码时,我遇到了以下错误,这段代码应该创建一个不使用泛型的自定义Java数组。我很确定这是因为没有正确创建数组,但我不确定 任何帮助都将不胜感激!谢谢 当前编译错误摘录: 51: error: unreported exception Exception; must be caught or declared to be thrown strList.add("str1"); 自定义数组类: public class MyList { Object[] data; // li

当我试图编译这段代码时,我遇到了以下错误,这段代码应该创建一个不使用泛型的自定义Java数组。我很确定这是因为没有正确创建数组,但我不确定

任何帮助都将不胜感激!谢谢

当前编译错误摘录:

51: error: unreported exception Exception; must be caught or declared to be thrown strList.add("str1");
自定义数组类:

public class MyList {

Object[] data; // list itself. null values at the end
int capacity; // maximum capacity of the list
int num; // current size of the list
static final int DEFAULT_CAPACITY = 100;

public MyList() {
    this(DEFAULT_CAPACITY); // call MyList(capacity).
}
public MyList(int capacity) {
    this.capacity = capacity;
    data = new Object[capacity]; // null array
    num = 0;
}
public void add(Object a) throws Exception {
    if (num == capacity) {
        throw new Exception("list capacity exceeded");
    }
    data[num] = a;
    num++;
}
public Object get(int index) {
    // find the element at given index
    if (index < 0 || index >= num) {
        throw new RuntimeException("index out of bounds");
    }
    return data[index];
}
public void deleteLastElement() {
    // delete the last element from the list
    // fill in the code in the class.
    if (num == 0) {
        throw new RuntimeException("list is empty: cannot delete");
    }
    num--;
    data[num] = null;
}
public void deleteFirstElement() {
    // delete first element from the list
    for (int i = 0; i < num - 1; i++) {
        data[i] = data[i + 1];
    }
    data[num - 1] = null;
    num--; // IMPORTANT. Re-establish invariant
}


public static void main(String[] args) {
    MyList strList = new MyList();
    strList.add("str1");
    strList.add("str2");
    System.out.println("after adding elements size =" + strList);
}


}
公共类MyList{
对象[]数据;//列出自身。末尾为空值
int capacity;//列表的最大容量
int num;//列表的当前大小
静态最终int默认_容量=100;
公共MyList(){
此(默认容量);//调用MyList(容量)。
}
公共MyList(内部容量){
这个。容量=容量;
数据=新对象[容量];//空数组
num=0;
}
公共void添加(对象a)引发异常{
如果(num==容量){
抛出新异常(“超出列表容量”);
}
数据[num]=a;
num++;
}
公共对象get(int索引){
//在给定索引处查找元素
如果(索引<0 | |索引>=num){
抛出新的RuntimeException(“索引超出范围”);
}
返回数据[索引];
}
public void deleteLastElement(){
//从列表中删除最后一个元素
//在课堂上填写代码。
如果(num==0){
抛出新的RuntimeException(“列表为空:无法删除”);
}
num--;
数据[num]=null;
}
公共void deleteFirstElement(){
//从列表中删除第一个元素
for(int i=0;i
您需要声明
main
可以通过以下操作引发异常:

public static void main(String[] args) throws Exception{
...

将strList.add(…)放入
try catch
块中:

...
try{
    strList.add("str1");
    strList.add("str2");
} catch(Exception e){ 
    e.printStackTrace();
}

您永远不需要声明
抛出运行时异常
,我想您的意思是
抛出异常
。两者都可以工作。但是为了通用性,
抛出异常
更好。在这种情况下捕获RuntimeException不会修复编译器错误。不,“两个工作”都是错误的,只有@MarkRotterVeel提出的工作渴望帮助或农场代表点?在过去的几分钟里,我看到了你的三个答案,但都有缺陷。在发帖之前,不要试图做一个正确的回答,并重新检查你的答案。在回答之前,尽可能少地搜索重复的答案。如果答案被接受,你应该将其标记为“如此…”。。。(答案分数下的V符号)