所以我有一个程序用于存储员工记录,例如ID#,姓名,开始日期等。当用户输入员工ID号并按下删除按钮时,应搜索arraylist以及该员工ID存在于arraylist中的所有员工的数据应该从arraylist中删除。我可以添加和显示所有数据,但我无法弄清楚如何在arraylist中搜索ID号,然后删除该员工的所有数据。任何帮助都将不胜感激。到目前为止,我已经为删除按钮添加了我的代码,以及一些其他代码来显示数据的存储方式。
public class EmployeeRecords extends javax.swing.JFrame {
ArrayList <employees> employees = new ArrayList <employees>();
...
删除按钮代码:
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = idInput.getText();
boolean idCheck = employees.contains(id);
if (idCheck = true){
index = employees.indexOf(id);
employees.remove(index);
}
else {
errorLabel.setText("Employee not found. Please try again.");
}
}
添加按钮代码:
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
employees e;
String id, firstName, lastName, salary, startDate;
id = idInput.getText();
firstName = firstInput.getText();
lastName = lastInput.getText();
salary = salaryInput.getText();
startDate = dateInput.getText();
e = new employees(id, firstName, lastName, salary, startDate);
employees.add(e);
}
员工类:
class employees {
String id, firstName, lastName, salary, startDate;
employees (String _id, String _firstName, String _lastName, String _salary, String _startDate) {
id = _id;
firstName = _firstName;
lastName = _lastName;
salary = _salary;
startDate = _startDate;
}
}
答案 0 :(得分:0)
ArrayList <employees> employees = new ArrayList <employees>();
String id = idInput.getText();
boolean idCheck = employees.contains(id);
对象的ArrayList肯定不包含String id。
P.S。正如Jim所说,Employee类必须覆盖equals方法,该方法必须仅比较id(不是好主意)或使用Map&lt; String,Employee&gt;保留你的清单。然后你可以简单地调用remove方法,不需要检查是否有关键。