Wednesday 2 March 2016

java - Can't adding objects in ArrayList?



Hi I am trying to add an object into an Arraylist, I am using Java. But it does not work as I intended.



Let's say we have a class Sentence, so the code looks like




ArrayList result = new ArrayList();
for (int i =0; i<10;i++)
{
Sentence s = new Sentence(i.toString(),i);
//there is a string and an int in this Sentence object need to be set
result.add(s);
}



The above one works correctly. But I wish to speed up my code, so I try to only new one obejct, the code become:



ArrayList result = new ArrayList();
Sentence s = new Sentence(" ",0);
for (int i =0; i<10;i++)
{
s.setString(i.toString());
s.setInt(i);
result.add(s);
}



However, in this case, my result will become empty. I think I do change the content in the object s, but I don't know why it does not work during the result.add(s).



Many thanks to your reply.


Answer



Your s variable is always referring to the same object. It looks like you are adding the same object 10 times, which by the end of the for loop will have its string equal to "9" and its int equal to 9.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...