1

I have some java code here and I am creating an ADT for ArrayList (I know Java framework has one, but I just want to see what is underneath it). Here, I'm creating an a method that doubles the size of the array.

My question is, when I do oldArray=newArray, what happens in memory. My guess is that the variable pointing at the oldArray now points at the new array. But now, in memory, does that mean there are 2 variables pointing at the new array? And since there is no reference to the old array, will the garbage collector remove the old array from memory?

public void resize(int newCapacity) {
    E[] newData = (E[]) new Object[2*data.length];

    for(int i=0; i<data.length; i++) {
        newData[i] = data[i];
    }

    data = newData;
}
7
  • Yes to all of your deductions :-) Commented Feb 25, 2020 at 2:29
  • 1
    Could you try and use the same identifier names in your actual question as in the code, and create an example without spurious variables (newCapacity) that we can compile & run? Commented Feb 25, 2020 at 2:30
  • What is an ADT? Commented Feb 25, 2020 at 3:24
  • ADT is an abstract data type, a data structure that we design by ourselves Commented Feb 25, 2020 at 3:42
  • I could, but this was just an example I did Commented Feb 25, 2020 at 3:42

1 Answer 1

1

Both newData and data are references of the the object you created, they are located in the stack memory, according the way how works the garbage collector each reference will be removed when the execution path get the end of the scope, after the two references are removed the garbage goes to the heap in order to look object wich have no reference then tha object will be removed.

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

Comments

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.