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

2022-09-01 20:21:51

我想将一个对象添加到 一个 ,但每次我向 具有 3 个属性的 一个添加新对象时:,我都会收到一个错误。ArrayListArrayListobjt(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));
    }
}

这里,是我试图创建一个对象并将其传递给.DataArrayList

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);
        }
}

答案 1

创建对象时需要使用运算符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

答案 2

试试这个:

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

推荐