{"id":"list-methods-summary","slug":"list-toolbox","title":"The list toolbox","text":"Here are the list methods from this module and the last one. Three of them are new: `add(index, value)`, `isEmpty()` and `clear()`.\n\n| Method | What it does |\n|---|---|\n| `add(value)` | Adds the value to the end of the list. |\n| `add(index, value)` | Puts the value at the index. The values from there on move up one place. |\n| `get(index)` | Gives the value at the index. |\n| `set(index, value)` | Replaces the value at the index. |\n| `size()` | Gives the number of values. |\n| `remove(index)` | Removes the value at the index. Later values move down one place. |\n| `remove(value)` | Removes the first copy of the value, if there is one. For numbers: `remove(Integer.valueOf(n))`. |\n| `contains(value)` | `true` when the value is in the list. |\n| `indexOf(value)` | The index of the first copy of the value, or -1. |\n| `isEmpty()` | `true` when the list has no values. |\n| `clear()` | Removes every value. |\n\nThe methods that take an index crash with an `IndexOutOfBoundsException` when there's no such index. `add(index, value)` also accepts `size()` as the index, which adds to the end.\n\nThe three new ones at work:\n\n```java\nArrayList<String> line = new ArrayList<>();\nSystem.out.println(line.isEmpty());\nline.add(\"Bea\");\nline.add(\"Carl\");\nline.add(0, \"Abe\");\nline.add(2, \"Bill\");\nSystem.out.println(line);\nline.clear();\nSystem.out.println(line.isEmpty());\nSystem.out.println(line.size());\n```\n\n```output\ntrue\n[Abe, Bea, Bill, Carl]\ntrue\n0\n```\n\n`isEmpty()` says the same as `size() == 0`, but reads more like what you mean.\n\n### A program driven by commands\n\nMany programs are a loop that reads a command, does what it says, and goes round again until the user quits. A list makes a good memory for such a program: the last challenge of this module is a shopping list you run by typing commands.\n\nThat's the end of the MOOC's section on lists. Next come arrays: another way to keep many values, with a size that's fixed when the array is made.\n","task":"Fill in the blanks, so an urgent case goes to the front of the waiting list, and the program then empties the list and checks that it's empty. The program prints:\n\n```\n[Urgent case, Lotta, Sven]\nNobody is waiting\n```\n","kind":"fill","seed":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> waiting = new ArrayList<>();\n        waiting.add(\"Lotta\");\n        waiting.add(\"Sven\");\n        waiting.add([[0]], \"Urgent case\");\n        System.out.println(waiting);\n\n        waiting.[[clear]]();\n        if (waiting.[[isEmpty]]()) {\n            System.out.println(\"Nobody is waiting\");\n        }\n    }\n}\n","solution":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> waiting = new ArrayList<>();\n        waiting.add(\"Lotta\");\n        waiting.add(\"Sven\");\n        waiting.add(0, \"Urgent case\");\n        System.out.println(waiting);\n\n        waiting.clear();\n        if (waiting.isEmpty()) {\n            System.out.println(\"Nobody is waiting\");\n        }\n    }\n}\n","hints":["The front of the list is index 0, and `add(index, value)` takes the index first.","`clear()` removes every value, and `isEmpty()` tells whether any are left."],"tests":[{"name":"Output","stdin":"","expect":"[Urgent case, Lotta, Sven]\nNobody is waiting","hidden":false}],"require":[],"forbid":[],"more":[{"task":"A phone keeps a list of recently used apps, the most recent first. Write a method `markUsed(ArrayList<String> recent, String app)` that moves `app` to the front of the list: if it's already in the list, it's taken out of its old place first, so it's never in the list twice. The check builds a list of `maps`, `mail` and `camera`, calls `markUsed` with `camera` and then with `notes`, and prints the list after each call:\n\n```\n[camera, maps, mail]\n[notes, camera, maps, mail]\n```\n","kind":"code","seed":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> recent = new ArrayList<>();\n        recent.add(\"maps\");\n        recent.add(\"mail\");\n        recent.add(\"camera\");\n        markUsed(recent, \"camera\");\n        System.out.println(recent);\n    }\n\n    // Write the markUsed method here.\n}\n","solution":"import java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<String> recent = new ArrayList<>();\n        recent.add(\"maps\");\n        recent.add(\"mail\");\n        recent.add(\"camera\");\n        markUsed(recent, \"camera\");\n        System.out.println(recent);\n    }\n\n    public static void markUsed(ArrayList<String> recent, String app) {\n        if (recent.contains(app)) {\n            recent.remove(app);\n        }\n        recent.add(0, app);\n    }\n}\n","hints":["`recent.remove(app)` takes out the first copy of the app, and does nothing if it isn't there.","Then `recent.add(0, app);` puts it at the front. The method is `void`: it changes the caller's list."],"tests":[{"name":"Test 1","stdin":"","call":"ArrayList<String> recent = new ArrayList<>();\nrecent.add(\"maps\");\nrecent.add(\"mail\");\nrecent.add(\"camera\");\nmarkUsed(recent, \"camera\");\nSystem.out.println(recent);\nmarkUsed(recent, \"notes\");\nSystem.out.println(recent);\n","expect":"[camera, maps, mail]\n[notes, camera, maps, mail]","hidden":false},{"name":"Test 2","stdin":"","call":"ArrayList<String> recent = new ArrayList<>();\nmarkUsed(recent, \"clock\");\nmarkUsed(recent, \"clock\");\nSystem.out.println(recent);\n","expect":"[clock]","hidden":true},{"name":"Test 3","stdin":"","call":"ArrayList<String> recent = new ArrayList<>();\nrecent.add(\"chat\");\nrecent.add(\"music\");\nrecent.add(\"photos\");\nmarkUsed(recent, \"music\");\nSystem.out.println(recent);\nmarkUsed(recent, \"chat\");\nSystem.out.println(recent);\n","expect":"[music, chat, photos]\n[chat, music, photos]","hidden":true}],"require":[{"pattern":"\\.add\\s*\\(\\s*0\\s*,","message":"Put the app at the front with `add(0, app)`."}],"forbid":[]},{"task":"Write a shopping list program that reads commands until `quit`. The commands `add` and `remove` are followed by a line with an item.\n\n- `add`: add the item and print `Added ` and the item. If it's already on the list, print `bread is already on the list` (with the item's name) instead.\n- `remove`: remove the item and print `Removed ` and the item. If it isn't on the list, print `cheese is not on the list` (with the item's name) instead.\n- `show`: print each item as `- ` and the item, with a for-each loop, or `The list is empty` when there's nothing on it.\n- `quit`: print `Bye!` and stop.\n\nFor the input shown, the program prints:\n\n```\nAdded bread\nAdded apples\nbread is already on the list\ncheese is not on the list\nRemoved bread\n- apples\nBye!\n```\n","kind":"code","seed":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<String> items = new ArrayList<>();\n        while (true) {\n            String command = scanner.nextLine();\n            if (command.equals(\"quit\")) {\n                System.out.println(\"Bye!\");\n                break;\n            }\n            // Handle add, remove and show here.\n        }\n    }\n}\n","solution":"import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<String> items = new ArrayList<>();\n        while (true) {\n            String command = scanner.nextLine();\n            if (command.equals(\"quit\")) {\n                System.out.println(\"Bye!\");\n                break;\n            }\n            if (command.equals(\"add\")) {\n                String item = scanner.nextLine();\n                if (items.contains(item)) {\n                    System.out.println(item + \" is already on the list\");\n                } else {\n                    items.add(item);\n                    System.out.println(\"Added \" + item);\n                }\n            } else if (command.equals(\"remove\")) {\n                String item = scanner.nextLine();\n                if (items.contains(item)) {\n                    items.remove(item);\n                    System.out.println(\"Removed \" + item);\n                } else {\n                    System.out.println(item + \" is not on the list\");\n                }\n            } else if (command.equals(\"show\")) {\n                if (items.isEmpty()) {\n                    System.out.println(\"The list is empty\");\n                }\n                for (String item : items) {\n                    System.out.println(\"- \" + item);\n                }\n            }\n        }\n    }\n}\n","hints":["One `if` per command. For `add` and `remove`, read the item with another `scanner.nextLine()` inside that branch.","`items.contains(item)` decides between the two messages of `add`, and of `remove`. For `show`, `items.isEmpty()` tells when to print `The list is empty`."],"tests":[{"name":"Test 1","stdin":"add\nbread\nadd\napples\nadd\nbread\nremove\ncheese\nremove\nbread\nshow\nquit\n","expect":"Added bread\nAdded apples\nbread is already on the list\ncheese is not on the list\nRemoved bread\n- apples\nBye!","hidden":false},{"name":"Test 2","stdin":"show\nadd\nmilk\nshow\nremove\nmilk\nshow\nquit\n","expect":"The list is empty\nAdded milk\n- milk\nRemoved milk\nThe list is empty\nBye!","hidden":true},{"name":"Test 3","stdin":"add\neggs\nadd\nrice\nadd\ntea\nremove\nrice\nshow\nquit\n","expect":"Added eggs\nAdded rice\nAdded tea\nRemoved rice\n- eggs\n- tea\nBye!","hidden":true},{"name":"Test 4","stdin":"quit\n","expect":"Bye!","hidden":true}],"require":[{"pattern":"for\\s*\\(\\s*\\w+\\s+\\w+\\s*:","message":"Print the items for `show` with a for-each loop."}],"forbid":[]}]}