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.
regards
Simply lose the curly braces:
Also, there’s a bug here:
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 onArrays.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?