首页 > 技术文章 > 重写Euqals & HashCode

brant 2016-12-28 23:02 原文

package com.test.collection;

import java.util.HashMap;
import java.util.Map;


/**
 * 重写equals & hashcode
 * 
 * 1.如果两个对象的equals为true ,则hashCode也为true
 * 2.重写equals时,必须重写hashCode(保证equals为true ,hashCode也为true)
 * @author chenx
 *
 */
public class Student {

    
    public Student(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    private int id;
    private String name;
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (id != other.id)
            return false;
        return true;
    }
}

 

推荐阅读