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.

JLTChiu
  • 983
  • 3
  • 12
  • 28

4 Answers4

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.

Tim Destan
  • 2,028
  • 12
  • 16
  • Do you mean that my ArrayList will only get one object? and after my sample, it will only get the object with `i =9`? – JLTChiu Apr 24 '12 at 05:06
  • The list will contain 10 references to a single `Sentence`. That `Sentence` will have `i = 9`. – Cameron Skinner Apr 24 '12 at 05:07
  • 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. – Tim Destan Apr 24 '12 at 05:07
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.

Community
  • 1
  • 1
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
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.

Donald Herman
  • 314
  • 1
  • 5
  • 15
0

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

maxaxis
  • 81
  • 1
  • 5