java基础回顾--4、重写equals及hashcode方法

需要移出集合中的对象或使用 set 时,经常需要重写对象的equals及hashcode方法,在此记录下。

package com.csdn.demo.rewriteequals;


import java.util.Objects;

/**
 * 尺子
 *
 * @author tony
 */
public class Ruler {

    /**
     * 价格
     */
    private Double price;

    /**
     * 品牌
     */
    private String brand;

    public Ruler() {
    }

    public Ruler(Double price, String brand) {
        this.price = price;
        this.brand = brand;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public boolean equals(Object otherObject) {

        if (this == otherObject) {
            return true;
        }

        if (otherObject == null) {
            return false;
        }

        if (getClass() != otherObject.getClass()) {
            return false;
        }

        Ruler other = (Ruler) otherObject;
        // 品牌一样代表相同
        return Objects.equals(brand, other.getBrand());
    }

    @Override
    public int hashCode() {
        return Objects.hash(brand);
    }

    public static void main(String[] args) {
        Ruler ruler = new Ruler(3.5, "得力");
        Ruler ruler1 = new Ruler(4.5, "得力");
        Ruler ruler2 = new Ruler(4.5, "晨光");
        System.out.println(Objects.equals(ruler, ruler1));
        System.out.println(Objects.equals(ruler1, ruler2));
    }
}

 

 

你可能感兴趣的:(java基础)