Mahatir Said
Mahatir Said

Reputation: 269

Removing Object of ArrayList by using it's unique ID

I am having problems with the functions of the ArrayList. I'm trying to remove objects of an ArrayList by specifying their ID. I have a createEmployee method in my Main class:

public void createEmployee(){
    String typeofemployee = sc.nextLine();

    UUID uniqueID = UUID.randomUUID();
    String x = "" + uniqueID;
    System.out.println("The new ID of the " + typeofemployee + " is: " + uniqueID + ".");

    System.out.println("What's the name of the new " + typeofemployee + "?");
    name = sc.nextLine();
    System.out.println("What's the salary of the new " + typeofemployee + "?");
    salary = sc.nextDouble();
    Employee employee = new Employee(x, name, salary);

    switch (typeofemployee) {

        case "Employee":
            reusaxcorp.registerEmployee(employee);
            break;

        // other cases
    }
}

And I have an ArrayList, to which I add employees by registering them with the following method (down below there's the removeEmployee method).

public class ReusaxCorp extends Main {

Scanner input;
ArrayList<Employee> employees = new ArrayList<Employee>();
final String END_OF_LINE = System.lineSeparator();

public void registerEmployee(Employee employee){
    employees.add(employee);
}

public void retrieveEmployee() {
    for(Employee employee: employees){
        System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
        System.out.println(); // an empty line for each employee
    }
}

public void removeEmployee(){
    employees.remove(0); 
    /* I also tried this, but it doesn't work either
    Iterator<Employee> iter = employees.iterator();
    while(iter.hasNext()){
        for (int i = 0; i < employees.size(); i++) {
            System.out.println("Which eployee do you want to remove? Type in his/her ID. ");
            int number = input.nextInt();
            Employee employee = iter.next();
            if (employees.equals(number)) {
                employees.remove(i);
            }
        }
    }
    */
}

The only way I know of is just to write employees.remove(index) and removing an employee by specifying his index. So I want to know if it's possible to remove an employee by specifying his unique ID. Thank you.

Upvotes: 4

Views: 15597

Answers (5)

AxelH
AxelH

Reputation: 14572

Previous Java 8, we had to use the remove method. Since the ID is unique, this is a possible equals implementation.

public boolean equals(Object o){
    //check for instance and null

    Employee e = (Employee) o;
    return this.uid.equals(e.uid);
}

Then, simply call ArrayList.remove(Object)

list.remove(employeeToRemove);

This doesn't need to be the same instance, just to have the same UID, so you could simply do

Employee employeeToRemove = new Employee(UUID)
list.remove(employeeToRemove);

It might be a bit more useless to create an instance to remove another one, but it is also useless to loop since there is method to do it ;)

Note, with equals being implemented, you should implements hashcode to be safe.

public int hashcode(){
    return UID.hashcode();
}

! All my codes are simplistic and don't check for null to be shorter !

Upvotes: 1

Kayaman
Kayaman

Reputation: 73568

Use the removeIf introduced in Java 8 for the shortest code.

employees.removeIf(e -> e.getId().equals(id));

You might also want to consider using a Map, since the ids are unique and then you can access (and/or remove) an employee very easily and efficiently with just the id. You can also use Map.values() to get all the employees as a collection (though not a List).

Map<String, Employee> employees = new HashMap<>();
employees.put(e.getId().toString(), e); // Or use UUID directly as key
employees.remove(idToBeRemoved);

Upvotes: 13

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37604

Yes it's possible. One way would be to use an Iterator. You are using the wrong syntax for it. But your approach is correct. Change it to

public void removeEmployee(String id){
    Iterator<Employee> it = employees.iterator();
    while(it.hashNext()){
        Employee employee = it.next();
        if(employee.getId().equals(id)){
            it.remove();
            break;
        }
    }
}

The call to get the user input would be passed to the method removeEmployee.

Upvotes: 1

Arthur Eirich
Arthur Eirich

Reputation: 3638

Use smth. like that:

public void removeEmployee(int removeId) {
 Employee empToRemove = employees.get(removeId);
 Iterator<Employee> iter = employees.iterator();
 while(iterator.hasNext()){
  Employee emp = iterator.next();
  if(emp.equals(empToRemove)){
   iterator.remove();
  }
 }
}

Upvotes: 1

M. le Rutte
M. le Rutte

Reputation: 3563

Since Java 8 there is a removeIf() method. You can use it as follows:

employees.removeIf(employee -> employee.getId().equals(removeId));

Upvotes: 6

Related Questions