-2

For example, Let's say I have the code below:

ArrayList<String> A1 = new ArrayList<>();
A1.add("Hello");
A1.add("World");
A1.add("!");

Then I perform the following actions:

A1.remove(2);

So A1 is now ["Hello", "World"].

But how do the compiler perform this action? What will the pointer that points to "!" before point to after I perform the delete action? Apparently A1.get(2) is now an illegal operation and will cause IndexOutOfBounds Exception, and A1.size = 2. What happens to the space that is allocated for 3rd slot of the list in memory and how are all these processed at lower level?

Thank you!

Shuffle
  • 1
  • 2
  • 5
    You need to read about garbage collection in Java. Look it up. It’s too big of a subject to be covered in a single Stack Overflow question, sorry. – Ole V.V. Jan 10 '19 at 05:09
  • Maybe a duplicate of https://stackoverflow.com/questions/3798424/what-is-the-garbage-collector-in-java instead? – rrauenza Jan 23 '19 at 19:12

1 Answers1

3

ArrayList internally creates array and stores data in that. When you remove element from ArrayList:

  • If it is an last element, it will just place null in that last index of array.
  • If it is an non last element, it will shift all the element from index+1 to left 1 place. and in the last index it will place null.

So once the particular index of array is placed with null that the object which is placed there becomes de-referenced(If the same object is not referred by any other reference), and it will be available for garbage collector.

In your case at the 2nd index null will be placed and "!" becomes un-referenced. So it will be available for garbage collector.

Deepak Kumar
  • 1,246
  • 14
  • 38