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,

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.

Thank you Ezzaral. I do appreciate your help.

on an unrelated note, you should look at System.arraycopy() to copy parts of arrays

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.