How to add an object to an ArrayList in Java

前端 未结 5 602
有刺的猬
有刺的猬 2020-12-07 15:55

I want to add an object to an ArrayList, but each time I add a new object to an ArrayList with 3 attributes: objt(name, address, contact)

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 16:45

    Contacts.add(objt.Data(name, address, contact));
    

    This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.

    The correct way is:

    // object creation. 
    Data object1 = new Data(name, address, contact);      
    
    // adding Data object to ArrayList object Contacts.
    Contacts.add(object1);                              
    

提交回复
热议问题