Home » Java » Storing Custom Class objects in ArrayList

Storing Custom Class objects in ArrayList

Storing User-defined Class objects in Java ArrayList:

In the code discussed above we stored String Object in ArrayList collection but you can store any type of object which includes object of your user defined class.

Employee.java


package com.jwt.core;

public class Employee {
	private int empId;
	private String name;
	private int age;

	public Employee(int empId, String name, int age) {
		this.empId = empId;
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return "Employee[id=" + empId + ",Name=" + name + ",Age=" + age + "]";
	}

}

TestList.java


package com.jwt.core;

import java.util.ArrayList;

public class TestList {
	public static void main(String args[]) {
		// Creating user-defined class objects
		Employee emp1 = new Employee(001, "Raj", 27);
		Employee emp2 = new Employee(002, "Amit", 24);
		Employee emp3 = new Employee(003, "Sonu", 21);

		ArrayList<Employee> list = new ArrayList<Employee>();
		list.add(emp1);
		list.add(emp2);
		list.add(emp3);

		for (Employee emp : list)
			System.out.println(emp);
	}
}

Output

Employee[id=1,Name=Raj,Age=27]
Employee[id=2,Name=Amit,Age=24]
Employee[id=3,Name=Sonu,Age=21]



Previous Next Article

comments powered by Disqus