Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 293
user2988935 Avatar asked Dec 03 '25 21:12

user2988935


1 Answers

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);
}
like image 188
Trying Avatar answered Dec 06 '25 10:12

Trying