在我学习java时,我了解到比较2个字符串的正确方法是使用equals而不是“==”。这条线
静态字符串 s1 = "a"; 静态字符串 s2 = "a"; System.out.println(s1 == s2);
将输出 true 因为 jvm 似乎已经优化了此代码,以便它们实际上指向相同的地址。我试图用我在这里找到的一篇很棒的帖子来证明这一点
http://javapapers.com/core-java/address-of-a-java-object/
但地址似乎不一样。我错过了什么?
导入 sun.misc.Unsafe; 导入 java.lang.reflect.Field; 公共类 SomeClass { 静态字符串 s1 = "a"; 静态字符串 s2 = "a"; 公共静态 void main (String args[]) 抛出异常 { System.out.println(s1 == s2); //真的 不安全不安全 = getUnsafeInstance(); 字段 s1Field = SomeClass.class.getDeclaredField("s1"); System.out.println(unsafe.staticFieldOffset(s1Field)); //600 字段 s2Field = SomeClass.class.getDeclaredField("s2"); System.out.println(unsafe.staticFieldOffset(s2Field)); //604 } private static Unsafe getUnsafeInstance() 抛出 SecurityException, NoSuchFieldException,IllegalArgumentException,IllegalAccessException { 字段 theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeInstance.setAccessible(true); return (Unsafe) theUnsafeInstance.get(Unsafe.class); } }