简单的问题,但有些困惑 [英] Simple question but having some confusion
问题描述
String str1 ="abc";
String str2 ="abc";
if(str1 == str2)
System.out.println("Equal 1");
为什么我们不喜欢这个..?
我用谷歌搜索找到==仅比较对象的身份.但是它打印正确的答案为什么?
和equal方法比较内容.
why we don''t prefer this..?
i googled it find == compares only the identity of the objects.but it print right answer why?
and equal method compare the content .
推荐答案
进一步回答上一个答案.
以您的示例为例:
Further to the previous answer.
Taking your example:
String one = "abcd";
String two = "abcd";
System.out.println(one == two);
这将打印出true
作为两个参考的单个常量.但是要这样更改:
This will print out true
as both reference a single constant. However changing it thus:
String one = new String("abcd");
String two = new String("abcd");
System.out.println(one == two);
将导致输出false
.这两个对象包含相同的值[内容相等],但是是不同的对象[占用不同的内存地址].
使用.equals(Object)
而不是==
是进入Java的重要习惯.
will result in an output of false
. The two objects contain the same values [content is equal] but are different objects [occupy different memory addresses].
It is an important habit to get into in java, using .equals(Object)
rather then ==
.
== tests for reference equality.
.equals() tests for value equality.
因此,如果您实际上想测试两个字符串是否具有相同的值,则应使用.equals()(在少数情况下,可以保证两个具有相同值的字符串将由同一对象表示,除非: ).
Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).
== is for testing whether two strings are the same object.
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
重要的是要注意,==比equals()(单指针比较而不是循环)便宜得多,因此,在适用的情况下(例如,您可以保证只处理中间字符串),它可以表现出重要的性能改进.但是,这种情况很少见.
It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.
这篇关于简单的问题,但有些困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!