0

I'm a little confused with the following scenario.

If there is an array created like so:

Declaration:

int[] array1;

Instantiation:

array1 = new int[500];

But then, later on, I no longer require 500 elements, so I simply create a new array with the new size, like so:

array1 = new int[50]

There are various references around the code that access this array, like so:

for (x=0;x<array1.length;x++){
array1[x]+someValue
}

What happens to the memmory where the other 450 elements were? The array itself is still 'alive' is it not because I still have lots of references to it's name, so it can't be GC'd, so I'm a little confused how the GC'd works in this case.

Note I know that I should have used an arrayList in order to re-size, unfortunately, this isn't an option for me now as it would be a ton of work to change my code (18 classes in size) so I want to stick to array's at least for this project and manage them as best I can.

4

3 回答 3

2

In your example, you're simply reusing a variable, array1 to reference multiple objects throughout the execution of your code. This does not mean that every object you reference with array1 will be held in memory forever.

Try thinking of it this way. When you assign array1 = new int[500] you are allocating an array of size 500 somewhere in memory and referencing that chunk of memory with a variable named array1:

image of array1 pointing to the first array

Later, you assign array1 = new int[50], so array1 is now holding a reference to an entirely different object:

image of array1 pointing to the second array

The first array is eligible for garbage collection because nothing holds a reference to it anymore.

于 2013-08-05T18:29:17.217 回答
1

The old one will be waiting for GC to kick in and to be collected as long as there's no reference to older ones. With new you will create a complete new placeholder for the array.

于 2013-08-05T17:51:13.920 回答
0

Java has a magical mechanism called garbage collection that will reuse the memory of the old array and assign you a new one. All the original contents of the array with 500 elements will be lost when you call new again though.

于 2013-08-05T17:49:38.153 回答