重写Euqals & HashCode

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

 

posted @ 2016-12-28 23:02  陈小兵  阅读(263)  评论(0编辑  收藏  举报