hashcode方法返回該對象的哈希碼值。
hashCode()方法可以用來來提高Map里面的搜索效率的,Map會根據不同的hashCode()來放在不同的位置,Map在搜索一個對象的時候先通過hashCode()找到相應的位置,然后再根據equals()方法判斷這個位置上的對象與當前要插入的對象是不是同一個。
所以,Java對於eqauls方法和hashCode方法是這樣規定的:
*如果兩個對象相同,那么它們的hashCode值一定要相同;
*如果兩個對象的hashCode相同,它們並不一定相同。
如下代碼:
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)); } }