I recently got a mistake in my java project because of my misunderstanding. I have the following code:
Post post = new Post(); // Post is my custom class
List<Post> list = new ArrayList<Post>();
for( int i = 0; i < num; i++){
post.setTitle( TITLE[i] ); //TITLE[] is a array of String.
list.add(post);
}
And after that all of element in the List list is the same and equal to the post with the title TITLE[num-1]. I know I got a misunderstanding in this problem because when I put the contructor
Post post = new Post();
inside the loop for, every thing is Ok. But anybody can explain this for me, please? Thank you very much.
You have just created one Post object, so in the lines
post.setTitle( TITLE[i] ); //TITLE[] is a array of String.
list.add(post);
you are just changing the title of that Post and adding it to the list. At the end, you will have only one Post in the list, but multiple times.
Why? Because in fact, objects are references to locations in memory, so you are adding the same reference (same location) on each iteration.
How can you solve it? You can create a new object on each iteration:
for( int i = 0; i < num; i++){
Post post = new Post();
post.setTitle( TITLE[i] );
list.add(post);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With