Possible Duplicate:
Java Strings: “String s = new String(”silly“);”
我正在查看一些字符串示例,但我很困惑:
有什么区别
String one = new String("ONE");
和
String one = "ONE";
这是我有点困惑的例子
String one = new String("ONE");
String another_one = new String("ONE");
System.out.print(one.equals(another_one)); //-->true
System.out.print(one == another_one ); //-->false
同时
String one = "ONE";
String another_one = "ONE";
System.out.print(one.equals(another_one)); //-->true
System.out.print(one == another_one ); //-->true
为什么会这样呢?
最佳答案
String one = new String("ONE");
创建一个新对象。使用 equals 方法进行比较时会比较字符串本身,当它们完全相同时返回 true。使用“==”运算符进行比较时会比较对象,在本例中,自从您创建了一个新对象以来,这些对象并不相同。
String one = "ONE";
String another_one = "ONE";
这实际上并没有创建一个新对象,编译器将优化这两个语句,以便“one”和“another_one”都指向内存中的同一个对象,因为它们都引用相同的字符串文字。由于这里两个变量都指向同一个对象,因此“==”在这种情况下将返回 true。
关于java - java中 new String ("ONE") 和 String one = "ONE"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8295256/