public static void test_01(){
String s1 = "hello";
String s2 = "hello";
String s3 = "hel"+"lo";
String s4 = new String("hello");
String s5 = new String("hello");
String s6 = new String("hel"+"lo");
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s4==s5);
System.out.println(s4==s6);
System.out.println(s4.equals(s5));
System.out.println(s4.equals(s6));
System.out.println(s4.hashCode() == s5.hashCode());
System.out.println(s4.hashCode() == s6.hashCode());
}
程序返回结果:
true
true
true
true
false
false
true
true
true
true
解释:
1."“是比较基本类型的值是否相等,或者比较两个引用变量是否相等(也即是两个对象的地址是否相等是否指向的是同一快存储空间),比较的是栈中的内容是否相等。
2.Object类中的equal方法直接使用的是”"运算符比较的两个对象。在没有覆盖equal方法的情况下,equal 和“==”都是值比较,比较的都是引用,任何对象的equal都不等。
3.String 覆写了Object的equal方法和hashcode方法,用于比较两个独立对象的内容是否相同,也即比较的是堆中的内容是否相同。
4,。hashcode方法:返回的是对象在内存中的地址转成的一个int值,在没有覆盖hashcode方法的情况下,任何对象的hashcode值都不等。
5.hashcode约定:
如果equal比较的两个对象相等,hashcode值必须相等
如果equal比较的两个对象不相等,hashcode值不一定相等
如果hashcode比较的两个对象不等,equal必须不等
如果hashcode比较的两个对象相等,equal不一定相等