如何在 Java 中将对象添加到 ArrayList
我想将一个对象添加到 一个 ,但每次我向 具有 3 个属性的 一个添加新对象时:,我都会收到一个错误。ArrayList
ArrayList
objt(name, address, contact)
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));
}
}
这里,是我试图创建一个对象并将其传递给.Data
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);
}
}