equals and lists
The list methods contains, indexOf and remove(value) from module 14 all search the list. To decide whether a value in the list is the one they're looking for, they call equals. With Strings that has always worked, because String has an equals of its own that compares the letters. With objects of your own class, it works as soon as the class has its own equals, like the Seat from the previous step:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Seat> booked = new ArrayList<>();
booked.add(new Seat("A", 3));
booked.add(new Seat("B", 7));
booked.add(new Seat("C", 1));
System.out.println(booked.contains(new Seat("B", 7)));
System.out.println(booked.indexOf(new Seat("C", 1)));
booked.remove(new Seat("A", 3));
System.out.println(booked);
}
}public class Seat {
private String row;
private int number;
public Seat(String row, int number) {
this.row = row;
this.number = number;
}
public boolean equals(Object compared) {
if (this == compared) {
return true;
}
if (!(compared instanceof Seat)) {
return false;
}
Seat other = (Seat) compared;
return this.row.equals(other.row) && this.number == other.number;
}
public String toString() {
return this.row + this.number;
}
}true
2
[B7, C1]- Each
new Seat(...)in the parentheses is a brand-new object, not one of the objects in the list.containsfinds it anyway, because it compares withequals, and a seat in the list is equal to it. indexOfgives the index of the first equal seat, andremove(value)removes the first equal seat, as they did with Strings.- Printing a list prints each value with its
toString, between brackets and separated by commas.
Without the equals method in Seat, all three would miss: contains would print false, indexOf would print -1, and remove wouldn't remove anything. The seat they're given is never the very same object as one in the list, and the equals that every class gets only looks for the same object.
For lists, equals is all it takes. Some of Java's other collections, which come in part 8, also need a second method, hashCode.
Only once in the list
A common use is a list that holds each value only once: before adding, check that no equal value is in it yet.
Seat seat = new Seat(row, number);
if (booked.contains(seat)) {
System.out.println(seat + " is already taken");
} else {
booked.add(seat);
System.out.println("Booked " + seat);
}