Let me first premise my question with the fact that I am learning programming/data structures. Yes, I know that Java has a collections API to do what I am coding, but for the moment, I would rather learn the basic ideas first.
I am coding an ArrayList implementation and am curious about garbage collection when references become obsolete. So in my case I have a generic object array i.e E[] data = (E[]) new Object[size];
and have a method E set(int index, E item)
which will replace the data[index]
with item. Here is my method body:
public E set(int index, E item) {
if(index<0||index>size-1) throw new IndexOutOfBoundsException(); //Not relevant to question
E previousValue = data[index];
data[index]=null;
data[index]=item;
return previousValue;
}
On to my question. Is it necessary to make the object null even if it the index is going to be reassigned. It seems like I should, but the code looks redundant to me. Or if am correct, is there a less redundant looking way to code this? I would really appreciate more than a single sentence answer, I'm really curious about this topic.