3

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

4 Answers 4

4

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

for (Employee employee : al) {
   System.out.println(employee.name);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

1 Comment

Please explain your answer in detail.
1
Iterator<Employee> i=al.getIterator();
 while (i.hasNext()) {
  String name = i.next().name;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.