如何在Java中将对象添加到ArrayList

我想向中添加一个对象ArrayList,但是每次我向ArrayList具有3个属性的新对象添加时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);

}

}

回答:

new创建对象时需要使用运算符

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

要不然

Data objt = new Data(name, address, contact); // Creating a new object

Contacts.add(objt); // Adding it to the list

并且您的构造函数不应包含void。否则它将成为您班上的一个方法。

public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such

以上是 如何在Java中将对象添加到ArrayList 的全部内容, 来源链接: utcz.com/qa/419771.html

回到顶部