0

I try to add multiple object in ArrayList, this is my code

ArrayList<WordData> unique = new ArrayList<WordData>();
WordData tempWordData = new WordData(); 

        for(int i=0;i<3;i++)
        {
            String temp_word = word.get(i);
            tempWordData.addWord(temp_word);
            unique.add(tempWordData);               
        }

but, all the data in unique ArrayList was word.get(2), not word.get(0), word.get(1), word.get(2)

Please help, thanks

3 Answers3

2

When you add an element to the ArrayList, you add a reference to that element, if you change the element, that change will be reflected in the ArrayList.

You have to create a new WordData inside the loop:

ArrayList<WordData> unique = new ArrayList<WordData>();

for(int i=0;i<3;i++)
{
    WordData tempWordData = new WordData(); 
    String temp_word = word.get(i);
    tempWordData.addWord(temp_word);
    unique.add(tempWordData);               
}
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
0

Try initializing your WordData instance inside the loop:

ArrayList<WordData> unique = new ArrayList<WordData>();

for(int i=0;i<3;i++) {
    String temp_word = word.get(i);
    WordData tempWordData = new WordData();
    tempWordData.addWord(temp_word);
    unique.add(tempWordData);
}
Jesse Webb
  • 43,135
  • 27
  • 106
  • 143
0

You have to create a WordData object in every iteration:

ArrayList<WordData> unique = new ArrayList<WordData>();

    for(int i=0;i<3;i++)
    {
        WordData tempWordData = new WordData(); 
        String temp_word = word.get(i);
        tempWordData.addWord(temp_word);
        unique.add(tempWordData);               
    }
Panagiotis
  • 401
  • 4
  • 13