String重写了hashcode()方法,String类型的hash值是根据字符串的内容来决定的,并不是内存地址,只要两个String类型的字符串内容一致,那么两者的hashcode就相同。String为了节约内存比较特殊,因为很常用,所以定义为值一样的hashcode就一样,不同对象的hashCode 值一般来说不会相同,同一个对象的hashCode值肯定相同
package com.web;
public class Test55 {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
boolean b2= s1==s2;
System.out.println("b2 = " + b2);
System.out.println("s1==s2 = "+(s1==s2));
System.out.println("s1==s3 = "+(s1==s3));
System.out.println("s3==s4 = "+(s3==s4));
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println("s1.hashCode() = " + s1.hashCode());
System.out.println("s2.hashCode() = " + s2.hashCode());
System.out.println("s3.hashCode() = " + s3.hashCode());
System.out.println("s4.hashCode() = " + s4.hashCode());
System.out.println("-------------------------------------");
Student stu1 = new Student("wang1", 11);
Student stu2 = new Student("wang1", 11);
Student stu0 = stu2;
System.out.println("stu1.hashCode() = " + stu1.hashCode());
System.out.println("stu2.hashCode() = " + stu2.hashCode());
System.out.println("stu0.hashCode() = " + stu0.hashCode());
Student stu3 = new Student();
Student stu4 = new Student();
Student stu5 = stu4;
System.out.println("stu3.hashCode() = " + stu3.hashCode());
System.out.println("stu4.hashCode() = " + stu4.hashCode());
System.out.println("stu5.hashCode() = " + stu5.hashCode());
System.out.println("stu3 = " + stu3);
System.out.println("stu4 = " + stu4);
System.out.println("stu5 = " + stu5);
Integer i1 = new Integer(100);
System.out.println("i1.hashCode() = " + i1.hashCode());
Integer i2 = 100;
System.out.println("i2.hashCode() = " + i2.hashCode());
boolean b = i1==i2;
System.out.println("b = " + b);
System.out.println(i1.equals(i2));
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/e0fe8b9fb2064f80b441f0f92f482c47.PNG?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAZGp5ZGp5MzMzMw==,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)