如何在Java中将对象添加到ArrayList [英] How to add an object to an ArrayList in Java

查看:579
本文介绍了如何在Java中将对象添加到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象添加到 ArrayList ,但每次我将一个新对象添加到 ArrayList 有3个属性: objt(姓名,地址,联系方式),我收到错误。

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

此处,数据是我正在尝试创建对象并将其传递给 ArrayList 的类。

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


推荐答案

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

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

或者

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

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

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

这篇关于如何在Java中将对象添加到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆