Java Object

Object 类的方法、equals 与 hashCode 的约定、toString 与 getClass。

Intermediate
Key Points所有类的根是 Object;重写 equals 必须同时重写 hashCode;toString 决定打印内容。

Object 类的方法

Object is the root of every class, defining equals, hashCode, toString, getClass, clone and finalize. Subclasses override as needed, but getClass is final.

MethodPurpose
equals(Object)Logical equality, default is ==
hashCode()Hash bucket index
toString()Text representation
getClass()Runtime class (final)
clone()Shallow copy

equals 与 hashCode

Contract: if a.equals(b) then their hash codes must match. Overriding equals alone makes objects unfindable in HashMap / HashSet, since they land in different buckets.

Java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

public class EqualsHash {
    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);

        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println(a.hashCode() == b.hashCode());

        Set<Point> set = new HashSet<>();
        set.add(a);
        set.add(b);
        System.out.println(set.size());
    }
}
Output
false
true
true
1

toString 与 getClass

Without overriding toString you get ClassName@hexhash, useless in logs. Override it and both println and logging show something meaningful.

Java
class User {
    String name;
    int age;

    User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{name=" + name + ", age=" + age + "}";
    }
}

public class ToStringDemo {
    public static void main(String[] args) {
        User u = new User("Tom", 20);

        System.out.println(u);
        System.out.println(u.getClass().getSimpleName());
        System.out.println(u.getClass() == User.class);
    }
}
Output
User{name=Tom, age=20}
User
true

Friends & Partners