Java Arena
Step 3 of 7

contains and indexOf

The last module searched a list with a loop. Two list methods do that searching for you:

  • list.contains(value) is true when the value is in the list, and false when it isn't.
  • list.indexOf(value) gives the index of the value, or -1 when it isn't in the list. If the value is there more than once, you get the first index.
ArrayList<String> colors = new ArrayList<>();
colors.add("red");
colors.add("green");
colors.add("blue");
colors.add("green");

System.out.println(colors.contains("blue"));
System.out.println(colors.contains("pink"));
System.out.println(colors.indexOf("green"));
System.out.println(colors.indexOf("pink"));
Output
true
false
1
-1

Both compare with equals, the way you compare Strings yourself, so they also find text the user typed in. The comparison is exact: "Green" with a capital G is not in this list.

They work on number lists too: numbers.contains(7) and numbers.indexOf(7) look for the value 7.

Searching in an if

contains gives a boolean, so the call can be the condition of an if. With indexOf, check for -1 before you use the index:

ArrayList<String> queue = new ArrayList<>();
queue.add("Ines");
queue.add("Tomas");
queue.add("Yuki");

if (queue.contains("Tomas")) {
    System.out.println("Tomas is in the queue");
}

String name = "Yuki";
int index = queue.indexOf(name);
if (index == -1) {
    System.out.println(name + " is not in the queue");
} else {
    System.out.println(name + " has " + index + " people ahead");
}
Output
Tomas is in the queue
Yuki has 2 people ahead

Yuki is at index 2, and the index is exactly the number of people before her.

Your task

Challenge 1 of 3

The program reads a seat and says whether it's taken. Fill in the blank with the right list method. For the input B4 it prints:

Seat B4 is taken

Challenge 2

The list finishers holds the runners of a race in the order they finished. Read a name and print the place that runner finished in (the winner is place 1), or say they're not in the results. Use indexOf, without a loop. For the input Kim the program prints:

Kim finished in place 3

and for the input Otto it prints Otto is not in the results.

Challenge 3

Some visitors sign a guest book more than once. Read names until the line done, and keep each name only the first time it appears: add a name to the list only if the list doesn't contain it yet. Then print the names in the order they first signed, and how many different guests there were. For the input Ada, Ben, Ada, Cleo, Ben the program prints:

Ada
Ben
Cleo
3 different guests