0

i have a problem with the values of an ArrayList. If I read the values out after I created the ArrayList, it just gifs me the last Value. Array in Listview

I was able to verify, that the problem is in the ArrayList and not somewhere else, but i don't get why.

 ArrayList <SubCategory> list = new ArrayList<>();
 SubCategory temp = new SubCategory();

 temp.setId(SF_DIRECT);
 temp.setName(R.string.spell_subcategory_direct);
 list.add(temp);

 temp.setId(SF_INDIRECT);
 temp.setName(R.string.spell_subcategory_indirect);
 list.add(temp);

 temp.setId(SF_ELEMENTAL);
 temp.setName(R.string.spell_subcategory_elemental);
 list.add(temp);
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Lazale
  • 1
  • 1
  • 4
    You should create a new instance of `temp` rather than directly modify its attributes. – Luiggi Mendoza Jul 13 '21 at 20:51
  • 1
    You might want to look at https://stackoverflow.com/questions/19843506/why-does-my-arraylist-contain-n-copies-of-the-last-item-added-to-the-list – Progman Jul 13 '21 at 20:55
  • 3
    You currently add the same `temp` instance three times, they all are the same instance which you modify over and over again. – luk2302 Jul 13 '21 at 20:55
  • it works your way @LuiggiMendoza, but what is the problem? I ask, because I never had problems my way as far as I remember. I also did it that way because I gave temp some values, which were importent for several instances and I am normaly to lazy give the same attributs several times manually ^^ – Lazale Jul 13 '21 at 20:59
  • @luk2302 but why do I only get the last entry several times? I add them, not replace them. – Lazale Jul 13 '21 at 21:01
  • 2
    Because you add the **same instance** three times, you only have a single `SubCategory` instance and that instance first has the id SF_DIRECT, then SF_INDIRECT and then SF_ELEMENTAL. And the last update is the one that takes effect because that is the ... last update. If I write `int a = 2; a = 3;` you only see `a = 3` in the end. And you only see `SF_ELEMENTAL` because that is the last id you set. – luk2302 Jul 13 '21 at 21:05

0 Answers0