Как получить доступ к методу GetEmployeeDetails() с использованием объекта iterator

#java

#java

Вопрос:

Как я могу вызвать getEmployeeDetails() метод, используя объект Iterator?

Java:

 import java.util. * ;

class Employee {
    String empName;
    int empId;
    String email;
    String gender;
    float salary;
    public void GetEmployeeDetails() {
        System.out.println(empName   " "   empId   "   "   email   "    "   gender   "    "   salary);
    }
    Employee(String empName, int empId, String email, String gender, float salary) {
        this.empName = empName;
        this.empId = empId;
        this.email = email;
        this.gender = gender;
        this.salary = salary;
    }
}

public class EmployeeDB {
    public static void main(String[] args) {
        ArrayList<Employee> list=new ArrayList<Employee>();
        Scanner sc = new Scanner(System. in );
        System.out.println("Please Enter Number of Employee : ");
        int empcount = sc.nextInt();
        for (int i = 0; i < empcount; i  ) {
            System.out.println("Please enter the Employee name :");
            String empName = sc.next();
            int empId = sc.nextInt();
            String email = sc.next();
            String gender = sc.next();
            float salary = sc.nextFloat();

            Employee emp = new Employee(empName, empId, email, gender, salary);
            list.add(emp);
            //list.add(emp);
        }
        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            Employee i = (Employee) itr.next();
            System.out.println(i.empName);
        }
        Employee e = list.get(0);
        System.out.println(e);
    }
}
  

Ответ №1:

Ваш код будет выглядеть следующим образом, используя Iterator

 for (Iterator<Employee> it = list.iterator(); it.hasNext(); ) {
                it.next().GetEmployeeDetails();
            }
  

Здесь it.next() будет возвращен объект employee. Как только вы получите объект Employee, вы сможете вызвать GetEmployeeDetails() метод

Вы можете использовать для каждого цикла, используя следующий способ:

 for (Employee employee:list) {
            employee.GetEmployeeDetails();
        }
  

Используя лямбда-выражение, вы можете использовать приведенный ниже код:

 list.forEach(employee -> employee.GetEmployeeDetails());
  

Ответ №2:

Пожалуйста, измените имя вашего метода с GetEmployeeDetails() на getEmployeeDetails()

Вы можете вызвать метод внутри цикла с помощью i.getEmployeeDetails() или для сотрудника e с помощью e.getEmployeeDetails()

 Iterator itr = list.iterator();
while (itr.hasNext()) {
    Employee i = (Employee) itr.next();
    i.getEmployeeDetails();
}
  

Комментарии:

1. здесь не разрешен тип ‘void’ System.out.println(i.GetEmployeeDetails()); произошла ошибка

2. @SomeshGangwar Вы не можете передать метод System.out.println(), поскольку он имеет возвращаемый тип void. Просто измените свой код на i.getEmployeeDetails(). Как в приведенном выше коде.

Ответ №3:

Вы можете использовать его следующим образом:

     Iterator<Employee> itr = list.iterator();
while (itr.hasNext()) {
  itr.next()
      .GetEmployeeDetails();
}