[JAVA] 6. Java中的重写override

对于java中对象的比较,经常会需要对类内的equalshashCode函数进行重写,下面一一个简单的点类为例,IDEA提供了快速重写的方法,通过Generate->equals&hashcode就可以快速重写:

import java.util.Objects;

public class Point {
    private int x;
    private int y;

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

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

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}
posted @ 2020-04-22 22:12  莫等闲™  阅读(134)  评论(0)    收藏  举报