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));
    }
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值