刚学JAVA,编了个程序可以编译通过,运行时就出异常了。帮我看下,谢谢了。
//: c09:E09_StringContainer.java
//+M java E09_StringContainer
import java.util.*;/****************** Exercise 9 ******************
 * Create a container that encapsulates an array
 * of String, and that only adds Strings and gets
 * Strings, so that there are no casting issues
 * during use. If the internal array isn't big
 * enough for the next add, your container should
 * automatically resize it. In main(), compare
 * the performance of your container with an
 * ArrayList holding Strings.
 ***********************************************/
class StringContainer { //class container
private int size = 10;
private String[] strings = new String[size];
private int index = 0;
public int  setSize() { //if the array isn't big enough,resize 
return size = size*2;
}
public void add(String s) {//add string
if(index>=size) {
setSize();
}
strings[index] = s;//||Exception here||.
index++;
}
public void print(){//print the list.
for(int i = 0;i<strings.length;i++) {
System.out.println(strings[i].toString());
}
}
public int getSize() {//get the size 
return size;
}
public int getIndex() {//get the index which record the 
                                // real string's numbers。
return index;
}
}
public class E09_StringContainer {
public static void main(String[] args) {
StringContainer strc = new StringContainer();
String[] strs =     {"def","ghi","jkl","dadf","gfgai","gfadio","gaodafd","fdfdcvsfso","fdafdacims","fdafi","fdifadkm","daida","idak","aok","dia","fdm"};
for(int i =0;i<strs.length;i++) {
strc.add(strs[i]);//||exception||.
}
strc.print();
System.out.println(strc.getSize());
System.out.println(strc.getIndex());
}
}异常是这样:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at StringContainer.add(E09_StringContainer.java:26)
at E09_StringContainer.main(E09_StringContainer.java:46)

解决方案 »

  1.   

    数组索引超范围。LZ把下面的程序运行一下就明白了。public class Test {
    public static void main(String[] args){
     int size = 10;
     String[] strings = new String[size];
     size=20;
     System.out.print(strings.length);
    }
    }
      

  2.   

    楼上的不对!该这样:
    public class Test {
    public static void main(String[] args){
     int size = 10;
     int[] ints = new int[size];
     for(int i = 0;i<=ints.length;i++)
     {
    ints[i] = i ;
    System.out.println(ints[i]);
     }
     System.out.print(ints.length);
    }
    }
    这才是数组越界异常了。
      

  3.   

    setSize()方法只是将size的值增加到原来的两倍,而数组的大小并没有改变,这样当然会越界了。