2

Part1 throws an error while part2 does not, why?

 //part 1
 Object[] arr = new Object[10000000];
 Object[] arr1 = arr;
 for(int i = 0; i < 100; i++) {
     arr1[0] = new Object[10000000];
     arr1 = (Object[]) arr1[0];
 }

//part 2
Object[] arr1 = new Object[10000000];
for(int i = 0; i < 100; i++) {
   arr1[0] = new Object[10000000];
   arr1 = (Object[]) arr1[0];
}
1
  • Is this a homework question? Commented Mar 8, 2014 at 8:34

2 Answers 2

2

In your first snippet, you're retaining a reference to your original huge array, and therefore to every array that you create subsequently.

In your second snippet, you're throwing away the reference to the original huge array - in fact, you're throwing away references to each array except the one you've created, in every iteration of the loop. So that allows all but one of them to be garbage collected, and you only need enough heap space for two of the arrays at any point in the loop.

Sign up to request clarification or add additional context in comments.

Comments

1

because in second case you don't have live references for all Object[]

2 Comments

for all Object[] you mean arr1 or arr1[0]?
those are references, all the allocated i meant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.