java · level 2 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
== asks whether two objects are the same one, not alike.
Two Coin objects can hold the same values and still be two separate objects. == asks: are these the very same object? The free equals asks the same. To compare what is inside, write your own public boolean equals(Object other).
Object means any object at all. So first check : is it a coin? Then it: (Coin) other tells Java to treat it as a Coin, so you can compare the fields.
Sets and maps also call , which turns an object into a number. Equal objects must give equal numbers, so write that too: .
import java.util.*;
public class Main {
static class Coin {
private String name;
private int year;
Coin(String name, int year) { this.name = name; this.year = year; }
public boolean equals(Object other) {
if (!(other instanceof Coin)) { return false; }
Coin coin = (Coin) other;
return name.equals(coin.name) && year == coin.year;
}
public int hashCode() { return Objects.hash(name, year); }
}
public static void main(String[] args) {
Coin a = new Coin("penny", 1971);
Coin b = new Coin("penny", 1971);
System.out.println((a == b) + " " + a.equals(b));
System.out.println(new HashSet<>(List.of(a, b)).size());
}
} Whenever you write equals, write hashCode from the same fields.
guess first
Same book, two copies. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
static class Book {
private String title;
Book(String title) { this.title = title; }
}
public static void main(String[] args) {
ArrayList<Book> shelf = new ArrayList<>();
shelf.add(new Book("Holes"));
System.out.println(shelf.contains(new Book("Holes")));
System.out.println(shelf.size());
}
}
your turn
Your turn. When are two cards the same?
Finish equals on line 10 so two cards match only when both the suit and the number match. Then press run.
output
press run to see what happens
fix it
The album keeps a copy it should not. Fix it!
output
press run to see what happens
equalssays the two stamps match, yet the set keeps both. What else does a set use?- A set compares
hashCodenumbers first. Stamp only has the free one, which gives a different number for every object. - Add
public int hashCode() { return Objects.hash(country, year); }after theequalsmethod, then press run.
nailed it
you taught java what equal means. :D
==asks whether two boxes hold the very same object.- Write
equalsto compare the fields that matter. - Write
hashCodewithObjects.hashfrom the same fields.
new words in your collection
- instanceof
- cast
- hashCode
- Objects.hash
This lesson isn’t saved. A free account remembers every lesson you finish.