sanjay
sanjay

Reputation: 1020

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???

Upvotes: 3

Views: 2016

Answers (4)

sreenath
sreenath

Reputation: 499

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);
}

Upvotes: 2

Angad Tiwari
Angad Tiwari

Reputation: 1768

Iterator<Employee> i=al.getIterator();
 while (i.hasNext()) {
  String name = i.next().name;
}

Upvotes: 1

Bhavishya Prajapati
Bhavishya Prajapati

Reputation: 160

 System.out.println(al.get(index).name);

Upvotes: 1

NPE
NPE

Reputation: 500177

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

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

Upvotes: 4

Related Questions