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)
, I get an error.
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Plz enter Name : ");
String name = input.nextLine();
System.out.println("Plz enter Address : ");
String address = input.nextLine();
System.out.println("Plz enter ContactNo : ");
String contact = input.nextLine();
ArrayList<Data> Contacts = new ArrayList<Data>();
Data objt = new Data();
Contacts.add(objt.Data(name, address, contact));
}
}
Here, Data
is the class of which I'm trying to create an object and pass it to an ArrayList
.
public class Data {
private String name = "";
private String address = "";
private String cell = "";
public void Data(String n, String a, String c){
name = n;
address = a;
cell = c;
}
public void printData(){
System.out.println("Name\tAddress\tContactNo");
System.out.println(name + "\t" + address + "\t" + cell);
}
}
You have to use new operator here to instantiate. For example:
You need to use the
new
operator when creating the objector else
and your constructor shouldn't contain
void
. Else it becomes a method in your class.change Date to Object which is between parenthesis
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:
Try this one: