当前位置: 代码迷 >> J2SE >> 关于String字符串的比较。该如何解决
  详细解决方案

关于String字符串的比较。该如何解决

热度:69   发布时间:2016-04-24 02:22:13.0
关于String字符串的比较。
大家都知道
如果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()返回是字符串的内容 而两个内容是相同的 只是存放在了不同的堆空间 而这种从内容到堆空间地址的转换在这个==中是怎么做到的 我不太清楚
简单说 就是……

------解决方案--------------------
又是这样总问题 
String s1=new String("hello"); 
在虚拟机里 内存先创建 生成 "hello" 字符串;
然后由于 new String 内存创建一个新对象 隐藏对象 赋值给S1
S2 由于内存中已经生成了hello常量
所以你懂得 下面那句话打印出来看下就明白了 
Java code
                 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);
  相关解决方案