In most of the java application we need to create our own class and objects. It may be Employee, Address, Person details etc. In this article we will see how we can save user defined object in arraylist. Here I have created 2 java files: Employee.java, UserDefinedObjectInArrayList.java
package com.chetasmind.listPackage;
public class Employee {
private int empID;
private String empName;
private double empSalary;
public Employee() {
}
public Employee(int empID,String empName,double empSalary) {
this.empID = empID;
this.empName = empName;
this.empSalary = empSalary;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
@Override
public String toString() {
String empDetails = "Employee ID: "+this.empID+" Employee Name: "+this.empName+" Salary="+this.empSalary;
return empDetails;
}
}
package com.chetasmind.listPackage;
import java.util.ArrayList;
public class UserDefinedObjectInArrayList {
public static void main(String[] args) {
ArrayList<Employee> obj = new ArrayList<>();
Employee emp1 = new Employee(101,"Sagar",45000);
Employee emp2 = new Employee(102,"Rekha",85000);
Employee emp3 = new Employee(103,"Suresj",35000);
Employee emp4 = new Employee(104,"Subin",35000);
obj.add(emp1);
obj.add(emp2);
obj.add(emp3);
obj.add(emp4);
Employee resultObj;
for(int i=0;i<obj.size();i++) {
resultObj = obj.get(i);
System.out.println(resultObj);
}
}
}
If you run the above application, output will be :
Employee ID: 101 Employee Name: Sagar Salary=45000.0
Employee ID: 102 Employee Name: Rekha Salary=85000.0
Employee ID: 103 Employee Name: Suresj Salary=35000.0
Employee ID: 104 Employee Name: Subin Salary=35000.0
The above application is also present in my github repository.
If you are writing java applications for the first time, refer my Project structure article.