equals:比较的是内存中的数值内容是否相等
@Test
public void equalsDemo(){
String s1="gaoxinfu";
String s2="gaoxinfu";
String s3=new String("gaoxinfu");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s2.equals(s3));
}
String s1="gaoxinfu";
String s2="gaoxinfu";
String s3=new String("gaoxinfu");
1.从上面我们看到,s1="gaoxinfu",的值gaoxinfu这个在内存中没有,则会在内存中新分配一个内存;
s2="gaoxinfu",的值gaoxinfu这个在内存中已经有了,这个时候会直接使用上面的内存
2.String s3=new String("gaoxinfu");跟s2的创建不太一致,所以因为是new的,所以内存会重新分配区域
==:比较是内存中的地址是否相等
1.这里我们说的内存,是指堆内存,因为对象主要是存储在堆内存之中;
2.在不override上面的equals方法的前提下,实际上如果两个字符串如果==判断是相等的,
那么这两个字符串equals方法也一定是相等的,因为==指向的内存地址是一个,那么数据也是一个,所以必然是相等的;
@Test
public void equalsDemo(){
String s1="gaoxinfu";
String s2="gaoxinfu";
String s3=new String("gaoxinfu");
System.out.println("str1内存地址="+System.identityHashCode(s1));
System.out.println("str2内存地址="+System.identityHashCode(s2));
System.out.println("str3内存地址="+System.identityHashCode(s3));
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s2==s3);
}
hashCode