java中hashCode()方法的做用

       hashcode方法返回该对象的哈希码值。
      hashCode()方法能够用来来提升Map里面的搜索效率的,Map会根据不一样的hashCode()来放在不一样的位置,Map在搜索一个对象的时候先经过hashCode()找到相应的位置,而后再根据equals()方法判断这个位置上的对象与当前要插入的对象是否是同一个。
因此,Java对于eqauls方法和hashCode方法是这样规定的:
   *若是两个对象相同,那么它们的hashCode值必定要相同;
   *若是两个对象的hashCode相同,它们并不必定相同。java

以下代码:this

package demos;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by hu on 2016/3/26.
 */
public class Student {
    private String name;
    private Integer age;
    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

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

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

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

    public String toString() {
        return name + "'s age is " + String.valueOf(age);
    }

    public boolean equals(Object other) {
        if(this == other)
            return true;
        if(other == null)
            return false;
        if(!(other instanceof Student))
            return false;

        final Student stu = (Student)other;
        if(!getName().equals(stu.getName()))
            return false;
        if(!getAge().equals(stu.getAge()))
            return false;
        return true;
    }

    public int hashCode() {
        int result = getName().hashCode();
        result = 29*result + getAge().hashCode();
        return result;
    }

    public static void main(String[] args){
        Set<Student> set = new HashSet<Student>();
        Student s1 = new Student("ZhangSan", 13);
        Student s2 = new Student("ZhangSan", 13);
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        set.add(s1);
        set.add(s2);
        System.out.println(set);
        System.out.println(s1.equals(s2));
    }
}
相关文章
相关标签/搜索