java hashCode()方法是所有java对象都具备的一个方法,用于比较两个对象是否内容相同,请注意!是比较对象的内容是否相同,并不是比较栈内存或堆内存的所在地址是否相同,在java开发中,用aaa==bbb这样比较对象是否相等是不行的,因为new出来的对象永远为false,下面是java hashCode方法的使用案例,以map集合来比较。
public class MapDemo {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("name1", "zhangsan");
Map<String,String> map2 = new HashMap<String,String>();
map2.put("name1", "zhangsan");
System.out.println(map==map2); //false
int hashCode = map.hashCode();
int hashCode2 = map2.hashCode();
System.out.println(hashCode==hashCode2); //true
}
}假如要比map集合里面的对象内容是否相等,也应该用hashCode()方法来比较,案例如下。
public class MapDemo {
public static void main(String[] args) {
Map<String,Student> map = new HashMap<String,Student>();
map.put("学生1",new Student("张三", 20));
Map<String,Student> map2 = new HashMap<String,Student>();
map2.put("学生1",new Student("张三", 20));
System.out.println(map==map2); false
int hashCode = map.hashCode();
int hashCode2 = map2.hashCode();
System.out.println(hashCode==hashCode2); //true
}
}每个对象的equals(Object o)方法内部实际上使用的就是hashCode()方法来进行比较的。