Saturday 9 May 2015

Storing Java Object In ArrayList

Storing Java Object In ArrayList 


Now we will make a arraylist of java object. Many times our java application needs to store java object in arraylist . For this firstly we make a arraylist of User type(In this program). Then store object of user in this.  

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListOfObject {


    public static void main(String[] args) {
    ArrayList<User> arr = new ArrayList<User>();   
    arr.add(new User("Raja", 20));
    arr.add(new User("Ariseter", 5));
    arr.add(new User("ManSingh",15));
   
    Iterator<User> itr = arr.iterator();
    while (itr.hasNext()) {
        User user = itr.next();
        System.out.println("Name="+user.getName()+" Age="+user.getAge());
    }
       
    }   

}


class User{
    private String name;
    private int age;
   
    public User(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
   
}


Output:

Name=Raja Age=20

Name=Ariseter Age=5

Name=ManSingh Age=15



Related Posts: 

 


Storing Java Object In ArrayList






No comments:

Post a Comment