Hello All,

I am trying to double the size of an array and copy its contents to the new array. I keep getting the following errors with the following code snippet:

 '.class' expected

not a statement

Here is my code:

 private void cpyArray()
      {
         if(itemCount == item.length)
            Doll [] temp = new Doll[item.length * 2];

         for(int i = 0; i < item.length; i++)
            temp [i] = item[i];
         item =temp;          
      }

Can anyone tell me what I am doing wrong? Any help would be appreciated.

Thank you,

Edited 3 Years Ago by mike_2000_17: Fixed formatting

The problem is that here

if(itemCount == item.length)
Doll [] temp = new Doll[item.length * 2];

you are just declaring a variable - not performing any useful operation. That variable will go out of scope immediately after it's declaration. I think what you actually want is this block

private void cpyArray()
{
    if(itemCount == item.length){
        Doll[] temp = new Doll[item.length * 2];
        
        for(int i = 0; i < item.length; i++)
            temp [i] = item[i];
        item =temp;
    }
}

(And please use [ code ] tags whenever you post code to the forums.)

Edit: Also, consider that you can use System.arraycopy() or Arrays.copyOf() to copy arrays without having to loop and copy every element.

This question has already been answered. Start a new discussion instead.