new com.foo.Bar()
如果args [0]为“2345”。 输出是 1540226 1540226 1540226 假。 为何错误?可以将实习字符串与==进行比较,对吗?
答案 0 :(得分:2)
Interned字符串只能使用==与其他实习字符串进行比较,并且只有在实习字符串值相同时才会返回true,即
String a = "a";
String b = "b";
String a2 = "a";
String c = a;
String d = a;
a == a2; //true
a == "a"; //true
a == new String("a"); //false
c == d; // true;
(a + a) == "aa"; // false
答案 1 :(得分:1)
您正在检查有价值的参考? " 2345" .equals(m1)是对的。
答案 2 :(得分:1)
String
是一个对象,所以当你使用==
时,你没有检查值是否等价,你正在检查一个String对象是否与另一个在同一个内存位置。 / p>
如果要测试对象之间的值等效性,请使用.equals()
答案 3 :(得分:1)
Just because one instance of a string is interned, doesn't mean that others are. In this case, "2345"
is a string constant and is thus automatically interned, but there's nothing that requires the JVM to automatically intern the arguments to main
. To my knowledge, there's nothing that explicitly prohibits the JVM from doing that, but it doesn't seem to be happening.
答案 4 :(得分:0)
通过“==”,您正在检查并比较字符串的“引用”值。使用“equals”可以比较两个给定字符串的“内容”。
hashCode返回m1,args [0]和“2345”的类似值,因为作为实习字符串,它们具有类似于SOP中所示的参考值。使用代码示例,这是它初始化的方式:
String someString = "string_info"
//Interning. Constant pool is checked for "string_info" and the reference is assigned to someString variable if "string_info" is found in constant pool.
但是,当string作为参数传递时,实际上这是作为新的字符串对象创建的。新对象在内存中创建,因此您的代码m1 ==“2345”返回false。举个例子,这就是它的初始化方式:
String someString = new String(“string_info”)//首先在内存中创建一个新的String对象,然后使用常量池查找引用“string_info”的赋值。