奇怪的异常。帮我看下,谢谢了

yasu1984 2007-07-19 05:32:42
刚学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)
...全文
198 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
huangyuguang 2007-07-19
  • 打赏
  • 举报
回复
setSize()方法只是将size的值增加到原来的两倍,而数组的大小并没有改变,这样当然会越界了。
july1732 2007-07-19
  • 打赏
  • 举报
回复
楼上的不对!该这样:
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);
}
}
这才是数组越界异常了。
realcbb 2007-07-19
  • 打赏
  • 举报
回复
数组索引超范围。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);
}
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧