×

java · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.