Java : Adding objects to a list of objects

前端 未结 2 496
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 00:36

Its very simple but somehow not working (weird!!).

I have a List of a class type. I am adding objects to the list in a for loop. Up till adding object everything is Ok,

2条回答
  •  无人共我
    2021-01-25 01:26

    When populating the list, you are repeatedly adding references to the same object. To fix, move the myClassObj initialization into the loop:

    for(int i=0;i

    This will create a separate object for every element of the list.

提交回复
热议问题