首页 > 其他 > 详细

重写equals和hashCode

时间:2017-09-06 12:45:09      阅读:269      评论:0      收藏:0      [点我收藏+]
package com.fz.song.hashCode;

import java.awt.*;

/**
 * Created by sfz on 2017/9/6.
 */
public class Cat {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    /**
     * 重写equals方法:重写了equals,就一定要重写hashCode方法.切记!
     *
     * @param obj
     * @return
     */
    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Cat)) {
            return false;
        }
        Cat obj1 = (Cat) obj;
        return obj1.getName().equals(this.getName()) && obj1.getAge() == this.getAge();
    }


    /**
     * 重写hashCode方法.
     *
     * @return
     */
    @Override
    public int hashCode() {
        int result = 17;
        result = result * 31 + name.hashCode();
        result = result * 31 + age;

        return result;
    }
}

 

重写equals和hashCode

原文:http://www.cnblogs.com/songfahzun/p/7483866.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!