We have the code:
Iterator<Object> it = new Collection<Object>(){/*...implementation...*/}.iterator();
Q: will the garbage collector remove the object that I created to express the collection? Formally, we have no references to this object, but it (Iterator <Object>)
is still connected with the interior of our object of anonymous class.
In other words, consider the code:
Iterator<Object> it = new Collection<Object>(){ // String (1)
private Object[] array;
public Iterator<Object> iterator(){
/*Here, an iterator that references this.array is returned
+ Performing its tasks*/
}
/* + other implementation...*/
}.iterator();
Then will GC remove the object created in the first line, which we objectively do not have a link to? //String (1)
For those who are particularly fond of writing pseudo-answers, here is the code for how my iterator looks like:
Iterator<Object> it = new Collection<Object>() { // String (1)
private Object[] array2;
@Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
Object[] array;
{
array = array2;
}
@Override
public boolean hasNext() {
// We do what is necessary
return false;
}
@Override
public Object next() {
// We do what is necessary
return null;
}
};
}
/* + other implementation... */
}.iterator();
Small additional Q:
Can I rename "array2", which is in the implementation of Collection, to "array"? Then How can I use this in the implementation of Iterator?
return new Iterator<Object>() {
Object[] array;
{
array = array2; // array = array ? It doesn't work. How refer to array above
}
// and so on...
About duplication... It's not this question. Maybe it looks like, but I want to receive the answer to my question about DELETING. Will this happen or no, and why? + It's important to receive the answer for additional question. That question can help someone to understand the answer to mine question, but not me.