重写equals和hashCode

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;
    }
}
原文地址:https://www.cnblogs.com/songfahzun/p/7483866.html