Java 如何仅使用 add 方法在我的集合中添加对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19961062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:51:01  来源:igfitidea点击:

How to add an object in my collection by only using add method?

javaobjectcollections

提问by user2988935

I have to create a collection of Name,Address,Age.How do I create this as a collection object in java.

我必须创建一个 Name、Address、Age 的集合。如何在 java 中将其创建为集合对象。

My snippet is as follows:

我的片段如下:

public class DataCollection implements java.io.Serializable{

    private String Name;
    private String Address;
    private int Age;
}

And I have the getter and setter methods...

我有 getter 和 setter 方法......

In the main method, how do I create this as a collection??

在 main 方法中,如何将其创建为集合?

list.add(new DataCollection(??????) );

Can someone please help me on this?

有人可以帮我吗?

采纳答案by Trying

public class DataCollection implements java.io.Serializable{

    private String Name;
    private String Address;
    private int Age;
    public DataCollection(String name, String address, int age){
            this.Name=name;
            this.Address=address;
            this.Age=age;
    }
}

After that create DataCollectionobjects:

之后创建DataCollection对象:

DataCollection d1 = new DataCollection("nik", "10/5 cross", 20);//creation of List collection

Now put the object inside a collection:

现在将对象放入一个集合中:

List<DataCollection> list = new LinkedList<DataCollection>();
list.add(d1);

You can iterate like below:

你可以像下面这样迭代:

List<DataCollection> list=new LinkedList<DataCollection>();
for(DataCollection d : list){
    System.out.println(d);
}

回答by blueblob

It is not clear from your question exactly what you are asking. I suspect the problem is that you are trying to allocate a List, which is an abstract class. You should be allocating a LinkedListor an ArrayList, or something of that sort. For a minimal example:

从你的问题中不清楚你在问什么。我怀疑问题在于您正在尝试分配一个List,它是一个抽象类。您应该分配LinkedListArrayList,或类似的东西。对于一个最小的例子:

import java.util.List;
import java.util.ArrayList;
public class DataCollection implements java.io.Serializable{

    private String Name;
    private String Address;
    private int Age;

    public static void main(String[] args){
        ArrayList<DataCollection> list = new ArrayList<DataCollection>();
        list.add(new DataCollection());
    }   
}

Then you can use list.get(index)to access the item in the list and set a name. The other problem may be that you want to pass arguments in when you create the object (such as the name, address, and age. If that is what you want to do, you need to look up overloading constructors.

然后您可以使用list.get(index)访问列表中的项目并设置名称。另一个问题可能是您想在创建对象时传入参数(例如名称、地址和年龄。如果这是您想要做的,则需要查找重载构造函数