Java在ADT构造函数异常中定义最大长度时发生

时间:2015-09-13 08:08:49

标签: java eclipse list

我正在编写一个简单的可扩展列表ADT,它使用一个数组来存储元素,当数组已满时,它会将列表中的所有元素复制到新数组中。代码如下:

public class ExpandedArray {

     private String[] elems;
     private int numElems;
     private int maxList = 5;

     public ExpandedArray() {
         elems = new String[maxList];
         numElems = 0;
     }

     public int size() {
         return numElems;
     }

     public String get(int position) {
         if(position < 0 || position >= numElems) {
             throw new IndexOutOfBoundsException("Out of bound!");
         }else {
             return elems[position];
         }
     }

    public void add(String s, int position) {
        // check if a list is full
         if(numElems == maxList) {
            // create a new larger array
            maxList = maxList*2;
            String[] elemsL = new String[maxList];
            // copy all the elements in the old list
            for(int i = 0; i < numElems; i++) {
                elemsL[i] = elems[i];
            }     
            elems = elemsL; 
        }

        if (position < 0 || position > numElems) {
            throw new IndexOutOfBoundsException("Out of bound!");
        }

        for (int i = numElems - 1; i >= position; i--) {
             elems[i + 1] = elems[i];
        }

        elems[position] = s;
        numElems++;
    }
 }

这很好用,但是当我将maxList = 5放在构造函数中时,会有一个异常:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ExpandedArray.add(ExpandedArray.java:45)
at Main.main(Main.java:8)

我知道在实现静态数组时,通常将maxList字段定义为final,但是当我尝试在构造函数中定义最大长度时,为什么会发生异常?

主要方法如下:

public class Main {

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

    ExpandedArray a = new ExpandedArray();

    a.add("hello",0);
    a.add(" ",1);
    a.add(",",1);
    a.add("my",3);
    a.add(" ",4);
    a.add("name",5);
    a.add("is",6);
    a.add(" ",6);
    a.add("bob",8);
    a.add(" ",8);

    for(int i = 0; i < a.size(); i++) {
        System.out.print(a.get(i));
    }       
}

我将maxList变量放在构造函数中,如下所示:

public class ExpandedArray {

private String[] elems;
private int numElems;
private int maxList;

public ExpandedArray() {
    elems = new String[maxList];
    numElems = 0;
    maxList = 5;
}

0 个答案:

没有答案