所以我需要更新一个具有相同id(字符串)的项目,所以我使用for-each循环来搜索该项目,我如何更新标题、描述和dueDate?我有一个todoItems
的数组列表// REQUIRES: idToFind is an id for an item in the to-do list
// MODIFIES: this
// EFFECTS: updates the to-do item with the specified id in the to-do list
public void updateTodoItem(String idToFind, String title,
String description, Date dueDate) {
for (TodoItem item: todoItems) {
if (item.getId().equals(idToFind)) {
}
}
}
我假设TodoItem类的字段有一些常规命名的setter。您可以执行以下操作
// REQUIRES: idToFind is an id for an item in the to-do list
// MODIFIES: this
// EFFECTS: updates the to-do item with the specified id in the to-do list
public void updateTodoItem(String idToFind, String title,
String description, Date dueDate) {
// Declare a TodoItem here (the target your are looking for)
TodoItem target = null;
for (TodoItem item: todoItems) {
if (item.getId().equals(idToFind)) {
target = item;
break;
}
}
// After the for we check if we have found the target item
if (target != null) {
// Use the setters of your todo object to set the values
// like
target.setTitle(title);
target.setDescription(description);
target.setDueDate(dueDate);
}
}
public void updateTodoItem(String idToFind, String title, String description, Date dueDate) {
for (TodoItem item: todoItems) {
if (item.getId().equals(idToFind)) {
item.setTitle(title);
item.setDescription(description);
item.setDate(dueDate);
System.out.println("Item Found!");
return; // You can also use 'break;'
}
}
System.out.println("Item Is Not Found!");
}