2

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.

2
  • Are you sure your result "will become empty"? You should be getting a list of 10 references to the same object. Commented Apr 24, 2012 at 5:05
  • 1
    this is not optimization, and you don't need it. Commented Apr 24, 2012 at 5:05

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you mean that my ArrayList will only get one object? and after my sample, it will only get the object with i =9?
The list will contain 10 references to a single Sentence. That Sentence will have i = 9.
Yes, that's what I mean. You need to call the constructor n times to get n objects. What you're doing now is just making modifications to one object, and storing n references to it.
3

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.

2 Comments

I see, so in this case, I can't avoid making these new objects.
yea of course, you need to make 10 Sentence objects in the memory.
0
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.

Comments

0

In order to prevent duplicate objects. Always instantiate them before using. This way your List would have n number of unique objects,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.