Adding tasks
- Java course
- Beginner
- Lesson 84/116
- 6 min
Add tasks with addTask.
Adding tasks: the addTask method
Now we will set up a second class called TodoList. This class keeps tasks in an ArrayList<Task> and adds new tasks with the addTask method.
class TodoList {
ArrayList<Task> tasks = new ArrayList<>();
void addTask(String title) {
tasks.add(new Task(title));
}
}The addTask method creates a new Task object and adds it to the list. So the caller only provides the title; object creation stays hidden inside the method.
TodoList and Task together
The TodoList class stores Task objects in a list. The addTask method adds one element per call.
TodoList list = new TodoList();
list.addTask("Shopping");
list.addTask("Homework");
System.out.println(list.tasks);
// [[ ] Shopping, [ ] Homework]When we print the list directly, we see all tasks inside brackets. Later we will produce a more readable output with the listTasks method.
Practice Write the addTask method
Inside the TodoList class, define void addTask(String title); the body should call tasks.add(new Task(title)). In main, call list.addTask("Shopping") and list.addTask("Homework"), then print with System.out.println(list.tasks).
Starter code
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
TodoList list = new TodoList();
// Add two tasks to the list
// Print the task list
}
}
class Task {
String title;
boolean done;
Task(String title) {
this.title = title;
this.done = false;
}
public String toString() {
return (done ? "[x] " : "[ ] ") + title;
}
}
class TodoList {
ArrayList<Task> tasks = new ArrayList<>();
// Define the addTask method: create a new Task and add to tasks
}Sample solution
// inside TodoList:
void addTask(String title) {
tasks.add(new Task(title));
}
// inside main:
list.addTask("Shopping");
list.addTask("Homework");
System.out.println(list.tasks);Expected output
[[ ] Shopping, [ ] Homework]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: add to the list
void addTask(String title) {
tasks.____(new Task(title));
}
void addTask(String title) {
tasks.add(new Task(title));
}
Explanation: tasks.add(new Task(title)) appends the new task.
2 Match call to result
| Term | Meaning |
|---|---|
addTask("X") |
X is added to the list |
list.tasks |
The list of all tasks |
new Task(title) |
A new task object |
System.out.println(list.tasks) |
Bracketed output |
3 What should the return type of addTask be?
- int Correct answer
- void
- Task
- String
Explanation: addTask returns nothing; it only appends.