0
public static void deleteEmployee(int empId) {
        Iterator<Employee> iterator = list1.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getEmpid() == empId) {
                System.out.println("The name of whose details deleted is  ::");
                iterator.remove();
            }
        }

    }

Here I am trying to delete node from arraylist based on employee id. But before deleting I want to show the details of particular employee. How can I do that?

4
  • iterator.next() gives you the employee node. Get all other details from it as you get employee Id like iterator.next().getEmpid() Commented Sep 13, 2013 at 6:56
  • Not all collections support remove but it would be fine with arraylist Commented Sep 13, 2013 at 6:59
  • if I do so then every time it will point to next to next element Commented Sep 13, 2013 at 7:37
  • @ASHISH, do not forget to accept the useful answer Commented Sep 13, 2013 at 8:52

2 Answers 2

4

What about storing emloyee in temporary variable?

public static void deleteEmployee(int empId) {
    Iterator<Employee> iterator = list1.iterator();
    while (iterator.hasNext()) {
        Employee employee = iterator.next();
        if (employee.getEmpid() == empId) {
            System.out.println("The name of whose details deleted is  ::" + employee.getName()); // or whatever property in employee
            iterator.remove();
        }
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

ya, its working fine. But can I use for each loop instead of Iterator?
No, if you would use for-each loop and modified iterated list it would throw ConcurrentModificationException. You would have to iterate through whole list and store values which you want to remove. Then in another loop iterate through these stored values and remove them from original list - much more complicated solution.
0

This has nothing to do with Iterator or List.

Look at Employee: does it it have a toString() implemenation that prints the details? If not, does it have getters for its properties? Use these with System.out.println.

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.