如何更新ArrayList中具有指定字符串的项目

时间:2015-09-29 19:42:45

标签: java arraylist updates

所以我需要更新我提供的具有相同id(字符串)的项目,因此我使用for-each循环来搜索项目,如何更新title,description和dueDate? 我有一个todoItems的ArrayList

// 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)) {


        }
    }
}

2 个答案:

答案 0 :(得分:0)

我假设你的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);

    }
}

答案 1 :(得分:0)

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!");
}