如何通过添加方法在我的集合中添加一个对象? [英] How to add an object in my collection by only using add method?

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

问题描述

我必须创建一个名称,地址,年龄的集合。如何在java中创建一个集合对象。



我的代码片段如下:

  public class DataCollection implements java .io.Serializable {

私有字符串名称;
private String地址;
private int Age;
}

我有getter和setter方法...



在主方法中,如何创建一个集合?

  .add(new DataCollection());有人可以帮我吗?

h2_lin>解决方案

  public class DataCollection implements java.io.Serializable {

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

之后创建 DataCollection objects:

  DataCollection d1 = new DataCollection(nik,10/5 cross,20 ); //创建List集合

现在将对象放在集合中:

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

您可以像下面这样迭代:

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


I have to create a collection of Name,Address,Age.How do I create this as a collection object in 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...

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

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

Can someone please help me on this?

解决方案

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 DataCollection objects:

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

这篇关于如何通过添加方法在我的集合中添加一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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