How to Create & Display Array of Objects in Java example

The Following code illustrates how to create an array of objects (i.e. storing of objects in an array) and display the values of each object.  In the below code, object of  Employee class  (fields: empcode, empName and salary) is stored in a arraylist and  each employee details are  retrieved  and  displayed back  using two methods.

Code :


package com.javaonline;
import java.util.*;
public class ArrayOfObjectsExample {

public static void main(String arg[])

{

ArrayList<Employee> empArr =new ArrayList<Employee>(); // arraylist to store objects

Employee emp1=new Employee(); // object 1

emp1.setValues("1001","XYZ", 10000); // values stored in the object

empArr.add(emp1); // object is stored in the array.

Employee emp2=new Employee(); // object 2

emp2.setValues("1002","ABC", 12000);

empArr.add(emp2);

Employee emp3=new Employee(); // object 3

emp3.setValues("1003","DEF", 15000);

empArr.add(emp3);


// Display values of the object from the array.
<span style="text-decoration: underline;"><strong>//Method 1</strong></span>

Iterator<Employee> ir= empArr.iterator();
Employee emp=new Employee(); // object 1

int i=0;

System.out.println("Output using Method 1\n");

while(ir.hasNext())

{

emp=(Employee)empArr.get(i);

ir.next();

System.out.println(i+1 +" : " + "Employee Name : "+ emp.getEmpName());

System.out.println(" Employee Code : "+ emp.getEmpcode());

System.out.println(" Salary : "+ emp.getSalary());

i=i+1;

}


<span style="text-decoration: underline;"><strong>//Method 2 since Java 1.5</strong></span>

System.out.println("\nOutput using Method 2\n");
i=0;

for (Employee empN : empArr)
{

System.out.println(i+1 +" : " + "Employee Name : "+ empN.getEmpName());

System.out.println(" Employee Code : "+ empN.getEmpcode());

System.out.println(" Salary : "+ empN.getSalary());

i=i+1;

}

}

}

// Class Employee


class Employee

{

String empcode="";

String empName="";

int salary=0;

public void setValues(String e, String eN, int s)

{

empcode=e;

empName=eN;

salary=s;

}
public String getEmpcode() {
return empcode;
}

public void setEmpcode(String empcode) {
this.empcode = empcode;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}

}

Output :

array of objects

You may also like

Leave a Reply

Be the First to Comment!