Java : Adding objects to a list of objects

前端 未结 2 491
伪装坚强ぢ
伪装坚强ぢ 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:16

    You need create a new myClassObj every time, your code uses the same object reference.

    List<myClass> myClassList = new ArrayList<myClass>();
    
        for(int i=0;i<someArray.length;i++){
            myClass myClassObj = new myClass(); // HERE
            myClassObj.setProperty1("value1");       
            ...
            System.out.println(myClassList.add(myClassObj));////////////////////////
        }
    
    0 讨论(0)
  • 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<someArray.length;i++){
        myClass myClassObj = new myClass(); // <---- moved this into the loop
        myClassObj.setProperty1("value1");
    

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

    0 讨论(0)
提交回复
热议问题