1. 程式人生 > >重寫equals和hashCode

重寫equals和hashCode

span pac getname spa .so ack amp eat imp

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