如何在 Java 中将对象添加到 ArrayList [英] How to add an object to an ArrayList in Java
本文介绍了如何在 Java 中将对象添加到 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个对象添加到 ArrayList
,但是每次我将一个新对象添加到具有 3 个属性的 ArrayList
时:objt(name, address, 联系)
,我收到一个错误.
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));
}
}
这里,Data
是我尝试创建对象并将其传递给 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屋!
查看全文