关于String字符串的比较。
大家都知道
如果String s1=new String("hello"); String s2="hello";
最后比较s1和s2 用==显示是不相等的 但是 直接使用对象名是调用了toString()方法
String toString()返回是字符串的内容 而两个内容是相同的 只是存放在了不同的堆空间 而这种从内容到堆空间地址的转换在这个==中是怎么做到的 我不太清楚
简单说 就是 在比较操作中 是怎么获取到两个hello所在的堆的地址的?还有以此附加个问题 怎样获取字符串的地址 就像其他对象直接输出 得到@xxxx一样
[解决办法]
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);