V
V
vapi2018-03-19 20:32:23
Java
vapi, 2018-03-19 20:32:23

Can 2 objects of the same type have the same reference name if the objects are created in a loop?

For experienced programmers, the question is ridiculous, but still I did not find the answer to it anywhere.
The loop creates 10 Song objects and adds them to the collection. Each iteration of the loop uses the same newSong reference variable.
Question: when the loop finishes its work in the ArrayList collection there will be only one object of type Song (the last one added) to which the "newSong" reference refers, and all other Song objects will be without reference?
public class Song {
}
public class Test {
public static void main(String[] args) {
ArrayList list=new ArrayList();
for(int i=0; i<10;i++){
Song newSong=new Song();
list.add(newSong);
}
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2018-03-19
@vapi

No. There will be 10 elements in the list, which are links to different instances of the Song class.
At the end of the loop, the variable newSong will no longer exist at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question