Storing Java Object In ArrayList

In previous post we have learn how to create java arraylist . If you are don’t know arraylist features then first read this post arraylist in java example . In this post we create java arraylist of String . But In java application we need to handle list of custom objects in java , how to store multiple objects in arraylist in java , arraylist of objects in java or  pojo class with arraylist in java like logic. It means we will create arraylist of object instead of string and get arraylist values in java .                                        Let’s try code for that
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

 

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 51 = 61