I am trying to create my own version of the ArrayList. I am implementing it in such a way that when you run my add method, it will create a new array of generic objects. Then it will copy each element to the new larger array and in the last element would be the new item they added.
public void add(E data)
{
if(this.arr == null)
{
this.arr = (E[]) new Object[size];
}
else
{
this.size++;
Object[] temp = (E[]) new Object[arr.length+1];
for(int i = 0; i < arr.length; i++)
temp[i] = arr[i];
temp[arr.length] = data;
this.arr = temp;
}
}
My code may not be correct since I did it really fast without testing it, not all of that should effect my question.
I know that in Java each object (in my case I am testing Integer objects) references a spot in memory. What I am not sure of is how the array works when copying objects in this part of my code:
for(int i = 0; i < arr.length; i++)
temp[i] = arr[i];
Each temp[i] spot is just referencing what arr[i] references and does not create a new spot in memory. Is this statement correct?
If I add 100 items, this means this method will run 100 times. If each element in the current array is just copied into new array of objects bigger by one, does that mean that none of the previous arrays will get deleted by the garbage collector since the new elements still point to the same memory spots?
If I create an array of size 1, it creates a block of memory that holds that array. If I then create a another array of size 2, the first element is copied to it and points to it, I then reassign my variable to point to that new array (this.arr = temp)/
Arr 1: [0]
Arr 2: [0][1] <- [0] points to the same object as [0] from arr 1
Arr 3: [0][1][2] <- [0] points to the same object as [0] from arr 1, [1] points to the same object as [1] from arr 1
Will the garbage collector not delete the space used by Arr 1, when one or more of its elements are pointed too by Arr 2? And the same for Arr 3? Do I need to re allocate every single element into a new array each time it grows?
(E)arr[i].