gpt4 book ai didi

java - 自增长数组java

转载 作者:行者123 更新时间:2023-11-29 03:34:27 25 4
gpt4 key购买 nike

题目是实现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));

}
}

最佳答案

Exception in thread "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];
}

关于java - 自增长数组java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16270928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com