简体   繁体   English

如何在运行时更改java中动态数组的值?

[英]how to change the value of a dynamic arrays in java during runtime?

this is my programm : 这是我的程序:

public class Basket {
private Item[] shops = { new Item("1",1)} ; 

public void storeItems(Item it){

        if (arraysIndex > shops.length){
            resizeArray(shops);

        }
        *shops[arraysIndex++] = {it};
        *shops[arraysIndex++] = {new Item(it.getName(),it.getPrice())};

    }

    public <T> T[] resizeArray(T[] arrayToResize){

        int newCapacity = arrayToResize.length *2;
        T[] newArray = (T[]) Array.newInstance(arrayToResize[0].getClass(), newCapacity);
        System.arraycopy(arrayToResize, 0, newArray, 0, arrayToResize.length);

        return newArray;
    }

}

in the lines the I indicated with * I will get such this error : 在我用*表示的行中我会得到这样的错误:

"Array constants can only be used in initializers" “数组常量只能用于初始值设定项”

which I don't know how to solve the problem in java please advice me about it. 其中我不知道如何解决java中的问题请指教我。

regards 问候

Simply lose the curly braces: 简直丢掉花括号:

    shops[arraysIndex++] = it;
    shops[arraysIndex++] = new Item(it.getName(),it.getPrice());

Also, there's a bug here: 此外,这里有一个错误:

    if (arraysIndex > shops.length){
        resizeArray(shops);
    }

Since array indices in Java start from zero, the correct comparison is if (arraysIndex >= shops.length) . 由于Java中的数组索引从零开始,因此正确的比较是if (arraysIndex >= shops.length)

Also, if you're using Java 1.6+, resizeArray() could be based on Arrays.copyOf() . 此外,如果您使用的是Java resizeArray() ,则resizeArray()可以基于Arrays.copyOf()

And, finally, you appear to be doing pretty much what ArrayList<T> does -- why not simply use the latter and not worry about reallocations etc? 而且,最后,你似乎正在做几乎所有的ArrayList<T> - 为什么不简单地使用后者而不担心重新分配等?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM