Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instance variable values from ArrayList Java

I have a class

public class Employee{

  public String name;

}

and

public static void main(){

    Employee e1= new Employee();
    e1.name="AAA";

    Employee e2= new Employee();
    e2.name="BBB";

    Employee e3= new Employee();
    e3.name="CCC";

    Employee e4= new Employee();
    e4.name="DDD";

    ArrayList<Employee> al= new ArrayList<>();

    al.add(e1);
    al.add(e2);
    al.add(e3);
    al.add(e4);
}

Now, I need to Iterate through the ArrayList and get the name property of each object. How can I do that. is there any direct method to do that???

like image 725
sanjay Avatar asked Feb 03 '26 04:02

sanjay


2 Answers

You could use a for-each loop to accomplish that:

for (Employee employee : al) {
   System.out.println(employee.name);
}
like image 59
NPE Avatar answered Feb 04 '26 18:02

NPE


You can do in 3 ways,

A simple iterative approach is

for(int i = 0,j = al.size(); i < j; i++) {
    System.out.println(al.get(i).name);
}

Using an enhanced for loop

for(Employee emp : al) {
   System.out.println(emp.name);
}

Using an iterator :

Iterator<Employee> itr = al.iterator();
while(itr.hasNext()) {
    emp = itr.next();
    System.out.println(emp.name);
}
like image 20
sreenath Avatar answered Feb 04 '26 17:02

sreenath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!