Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: resize method, can someone explain?

I am not sure how this method works. What I understand is that we create an temporary array with double the size of the theItems.length (theItems is another array). After, we copy the items to the temp array and in the end we write theItems = temp; (I am not sure why and what happens)(does it mean that theItems double its size too?). Can't we double the size of theItems without using temp?

private void resize() {
    String[] temp = new String[theItems.length*2];
    for (int i=0 ; i < noOfItems ; i++){
        temp[i]=theItems[i];
    }
    theItems=temp;
}
like image 489
Zuzu Avatar asked Feb 12 '26 10:02

Zuzu


2 Answers

I am not sure why and what happens

You are creating another array with more room for additional elements. Arrays have a fixed size in Java; once created, it cannot be changed. Here, the new array's length is double the old one. Then a simple for loop copies element references.

does it mean that theItems double its size too?

No, the array reference theItems is reassigned to the new, bigger array just created.

Can't we double the size of theItems without using temp?

You could just replace theItems with a new array, but then you just lost the reference to the original array that has all the items you want to retain, so that's not useful.

Here's what happens:

  1. Initial condition.

    theItems -> ["one", "two", "three"]
    
  2. New array created.

    theItems -> ["one", "two", "three"]
    
    temp     -> [null , null , null , null, null, null]
    
  3. Items copied.

    theItems -> ["one", "two", "three"]
    
    temp     -> ["one", "two", "three", null, null, null]
    
  4. The variable theItems is reassigned.

    theItems \       ["one", "two", "three"]  <- will be garbage collected.
             |
    temp   --+> ["one", "two", "three", null, null, null]
    

The variable temp will go out of scope, but theItems will still refer to the new array.

like image 65
rgettman Avatar answered Feb 15 '26 08:02

rgettman


String[] temp = new String[theItems.length*2]; creates an Array twice the size of theItems. So say if theItems was {"Hello", "Hi", "Goodbye", "Bye"} we would then have

__ __ __ __ __ __ __ __

as temp. Then

for(int i=0; i<noOfItems; i++){
    temp[i]=theItems[i];
}

Copies the items onto temp. So we would have:

"Hello", "Hi", "Goodbye", "Bye" __ __ __ __

(Four empty spaces at the end)

And then theItems=temp; assigns theItems to temp. This way the variable theItems will have four empty spaces, and more items can be added to it.

Note that the Arrays class already has a function built in to do this: Arrays.copyOf

like image 31
GBlodgett Avatar answered Feb 15 '26 07:02

GBlodgett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!