自增长数组java

时间:2013-04-29 03:50:49

标签: java arrays

问题是要实现三种方法get(int index)set(intindex)和构造函数SelfGrowingArray(),以便生成主方法中显示的句子。在编译时,我得到一个ArrayIndexOutofBoundsException,特别是这个错误:

[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));

}
}

2 个答案:

答案 0 :(得分:3)

  

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:-14

问题在于:

myList.get(-14)

您无法访问小于0的索引。修改get方法以支持负索引:

public Object get(int index) {
    if (index >= data.length || index < 0) {
        return null;
    }
    return data[index];
}

答案 1 :(得分:1)

因为它说你在get方法中尝试从索引[-14]中检索值时有异常,你应该检查索引值是否不低于零。

public Object get(int index)
{
   if (index >= data.length || index < 0)
     return null;
   return data[index];
}