大家都知道
如果String s1=new String("hello"); String s2="hello";
最后比较s1和s2 用==显示是不相等的 但是 直接使用对象名是调用了toString()方法
String toString()返回是字符串的内容 而两个内容是相同的 只是存放在了不同的堆空间 而这种从内容到堆空间地址的转换在这个==中是怎么做到的 我不太清楚
简单说 就是 在比较操作中 是怎么获取到两个hello所在的堆的地址的?还有以此附加个问题 怎样获取字符串的地址 就像其他对象直接输出 得到@xxxx一样
如果String s1=new String("hello"); String s2="hello";
最后比较s1和s2 用==显示是不相等的 但是 直接使用对象名是调用了toString()方法
String toString()返回是字符串的内容 而两个内容是相同的 只是存放在了不同的堆空间 而这种从内容到堆空间地址的转换在这个==中是怎么做到的 我不太清楚
简单说 就是 在比较操作中 是怎么获取到两个hello所在的堆的地址的?还有以此附加个问题 怎样获取字符串的地址 就像其他对象直接输出 得到@xxxx一样
别再用 == 比较 String 了
用 equals 比较吧纠结这些干什么
想获取String的哈希值,可以自己调用hashCode方法,即System.out.println(s1.hashCode());
想获取String的哈希值,可以自己调用hashCode方法,即System.out.println(s1.hashCode());
String s1=new String("hello");
在虚拟机里 内存先创建 生成 "hello" 字符串;
然后由于 new String 内存创建一个新对象 隐藏对象 赋值给S1
S2 由于内存中已经生成了hello常量
所以你懂得 下面那句话打印出来看下就明白了 String s1=new String("hello"); String s2="hello";
System.out.println(System.identityHashCode("hello"));
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
System.out.println(s1==s2);
class person{
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);
}
}
你运行一下看看 这个是没问题的。 这个结果是true