How to add an object to an ArrayList in Java

前端 未结 5 578
有刺的猬
有刺的猬 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:40

    Try this one:

    Data objt = new Data(name, address, contact);
    Contacts.add(objt);
    
    0 讨论(0)
  • 2020-12-07 16:41

    change Date to Object which is between parenthesis

    0 讨论(0)
  • 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);                              
    
    0 讨论(0)
  • 2020-12-07 16:47

    You need to use the new operator when creating the object

    Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step
    

    or else

    Data objt = new Data(name, address, contact); // Creating a new object
    Contacts.add(objt); // Adding it to the list
    

    and your constructor shouldn't contain void. Else it becomes a method in your class.

    public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such
    
    0 讨论(0)
  • 2020-12-07 16:50

    You have to use new operator here to instantiate. For example:

    Contacts.add(new Data(name, address, contact));
    
    0 讨论(0)
提交回复
热议问题