问题是为了生成主要方法中显示的句子,需要执行get(int index)
,set(intindex)
,set(intindex)
和构造函数SelfGrowingArray()
这三种方法。虽然它编译,我得到一个ArrayIndexOutofBoundsException
,具体地讲,这样的错误:自增长阵列java
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, You don't know you're beautiful]
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, You don't know you're beautiful, null, null, null, null, null, null, What doesn't kill you makes you stronger.]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -14
这里是我的代码,请大家帮忙:
public class SelfGrowingArray {
private Object[] data;
public SelfGrowingArray()
{
data = new Object[0];
}
public void set(int index, Object value)
{
if (index >= data.length) {
Object[] newArray = new Object[index + 1];
for (int i = 0; i < data.length; i++) {
newArray[i] = data[i];
}
data = newArray;
}
data[index] = value;
}
public Object get(int index)
{
if (index >= data.length)
return null;
return data[index];
}
public String toString()
{
if (data == null)
{
return "null";
}
int iMax = data.length - 1;
if (iMax == -1)
{
return "[]";
}
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++)
{
b.append(data[i]);
if (i == iMax)
{
return b.append(']').toString();
}
b.append(", ");
}
}
public static void main(String[] args) {
SelfGrowingArray myList = new SelfGrowingArray();
myList.set(14, "You don't know you're beautiful");
System.out.println(myList);
myList.set(21, "What doesn't kill you makes you stronger.");
System.out.println(myList);
System.out.println("myList.get(-14) " + myList.get(-14));
System.out.println("myList.get(14) " + myList.get(14));
System.out.println("myList.get(15) " + myList.get(15));
System.out.println("myList.get(31) " + myList.get(31));
System.out.println("myList.get(32) " + myList.get(32));
}
}
您是否尝试过使用调试器? – 2013-04-29 03:52:46
您的'toString()'方法是可怕的! – John3136 2013-04-29 03:55:02
对于John3136,为了公平地给予我们,我在这个问题中指定了我需要实现自己的方法。 – user2259570 2013-04-29 03:59:43