开发者

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

开发者 https://www.devze.com 2023-04-12 22:00 出处:网络
this is my programm : public class Basket { private Item[] shops = { new Item(\"1\",1)} ; public void storeItems(Item it){

this is my programm :

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

public void storeItems(Item it){

        if (arraysIndex > shops.length){
            开发者_StackOverflowresizeArray(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.

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).

Also, if you're using Java 1.6+, resizeArray() could be based on 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消