Reputation: 1023
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<Sentence> result = new ArrayList<Sentence>();
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<Sentence> result = new ArrayList<Sentence>();
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.
Upvotes: 2
Views: 9140
Reputation: 81
In order to prevent duplicate objects. Always instantiate them before using. This way your List would have n number of unique objects,
Upvotes: 0
Reputation: 464
ArrayList<Sentence> result = new ArrayList<Sentence>();
for (int i =0; i<10;i++)
{
result.add(new Sentence(i.toString(),i));
}
If you want to create less lines of code than you could use this example but it's not necessarily more optimized.
Upvotes: 0
Reputation: 37729
In the second case you adding 10 pointers to single Sentence
instance in ArrayList
.
You have to make 10 Sentence
to insert 10 pointer in ArrayList
.
I think you are messing with pass by value and pass by reference in Java, to clarify this, have a look at this post.
This post might also help you.
Upvotes: 3
Reputation: 2028
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
.
Upvotes: 5