前言
1)两个obj,如果equals()相等,hashCode()一定相等
2)两个obj,如果hashCode()相等,equals()不一定相等
3)两个不相等的对象,是存在有相同的 hashcode的可能性
4)在Object中,equals与==是等同的,都是比较引用是否相同,但是在String类中对equals进行了重写,进行的是值的比较
/** * @项目名称 longlonggo-sample * @文件名称 HashCode.java * @创建日期 2018年9月29日 * @创建作者 me@longlonggo.com */ package hashcode; /** * 说明: * equals()、hashcode()、==的区别 * @version 1.0 * */ public class HashCode { public static void main(String[] args) { String s1 = "a a"; String s2 = "a a"; Integer i1 = 1; Integer i2 = new Integer(100000); Integer i3 = new Integer(100000); System.out.println(s1.hashCode()); System.out.println(s1 == s2); System.out.println(i1 == i2); System.out.println(i2 == i3); System.out.println(i2.equals(i3)); System.out.println(i1.hashCode()); System.out.println(i2.hashCode()); System.out.println(i3.hashCode()); } } ---------------- 输出结果 ----------------- 94306 true false false true 1 100000 100000
参考:https://blog.csdn.net/qq_21163061/article/details/73606523