java - 将元素插入数组索引越界java

标签 java arrays exception insert

我制作了一个名为 NumList 的 ADT,并在 NumArrayList 类中实现了它

在实现的方法中,有一个 insert(int i, double value),其中将值插入到 array[i] 中。

int numItems 是一个跟踪数组元素的计数器。

public void insert(int i, double value)
{
    if (numItems >= items.length)
    {
        double[] tempItems = new double [items.length * 2];
        for(int j =0 ; j < items.length; j++ )
        {
            tempItems[j] = items[j];

        }

        tempItems[items.length] = value;
        items = tempItems;

    }

    else
    {
        if (i > numItems)
        {
            items[numItems] = value;
        }

        else 
        {
            for (int k = i; k < numItems; k++)
            {
                items[k+1] = items[k];
            }

            items[i] = value;
        }
    }

    numItems++;
}

这是我的方法,看起来很简单。

public static void main (String[] args)
{
    NumArrayList test;
    test = new NumArrayList();

    //System.out.println("this is how many initial items the initialized array has.");
    //System.out.println(test.items);
    test.insert(1, 0.1);
    System.out.println("have tried to insert value 0.1 @ position 1, that is the second element in array.");
    test.print();

是我的测试代码区域,内置于同一个类中。

我收到一个错误,编译器声称我在第 47 行或

处有一个 ArrayIndexOutOfBoundsException
tempItems[items.length] = value;

我相信它试图告诉我我的项目初​​始化是错误的,

private double[] items;
private int numItems;


public NumArrayList()
{
    items = new double[0];
    numItems = 0;
}

但是初始化已经被比我更好的程序员批准了,这些错误对我来说毫无意义。也许是关于我应该研究该计划的哪一部分的提示?

最佳答案

你的初始化肯定是错误的。合理的默认大小是多少?对于ArrayList,答案是10。您可以将其设置为任何您喜欢的值,但不能是零!如果将大小为 0 的数组的长度加倍,新数组的长度仍为 0。

int capacity; //stores the size of the array (items available)
int numItems; //stores how many items are actually stored in the array.

public NumArrayList()  {
    items = new double[10];
    numItems = 0;
    capacity = 10;
}

关于java - 将元素插入数组索引越界java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12630892/

相关文章:

Javascript:根据多个值过滤对象数组

c++ - 编译器错误 : looser throw specifier for destuctor

java - 在 finally block 中设置 reference = null?

python - 当在 bash 中调用的 python 脚本遇到错误时,如何停止 bash 脚本?

Java:什么是静态{}?

java - JDBC 中的表列标题不正确

java - Spring @Autowired 不工作 - BeanCreationException

java - 如何使数组的前半部分是从 0 到 7 的随机整数,后半部分是数组前半部分的随机成员,但只能选择一次

c - 如何从字符串中取出单词并将它们放入字符串数组中?在 C 中

单独文件中的 Java 静态嵌套类