我在的功能方面遇到问题ArrayList。我正在尝试通过指定ArrayList的对象来删除它们ID。createEmployee我Main班上有一个方法:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个ArrayList,通过使用以下方法注册员工来添加员工(下面是该removeEmployee方法)。
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);
}
}
}
*/
}
Run Code Online (Sandbox Code Playgroud)
我知道的唯一方法就是employees.remove(index)通过指定员工索引来写和删除该员工。因此,我想知道是否可以通过指定雇员的唯一ID来删除其雇员。谢谢。
从 Java 8 开始就有了一个removeIf()方法。您可以按如下方式使用它:
employees.removeIf(employee -> employee.getId().equals(removeId));
Run Code Online (Sandbox Code Playgroud)
使用removeIfJava 8中引入的最短代码。
employees.removeIf(e -> e.getId().equals(id));
Run Code Online (Sandbox Code Playgroud)
您可能还需要考虑使用Map,因为ID是唯一的,然后仅使用ID就可以非常轻松有效地访问(和/或删除)员工。您还可以Map.values()用来将所有员工作为集合(尽管不是List)。
Map<String, Employee> employees = new HashMap<>();
employees.put(e.getId().toString(), e); // Or use UUID directly as key
employees.remove(idToBeRemoved);
Run Code Online (Sandbox Code Playgroud)