java 比较与等于!比较字符串或对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10774559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CompareTo versus Equals! compares strings or objects?
提问by Navy Seal
Fast question
快问
I am comparing a String, should I use equals or compareTo? because I though equals distinguish 2 objects of type String and not just their value...
我正在比较一个字符串,我应该使用 equals 还是 compareTo?因为我虽然等于区分 2 个字符串类型的对象,而不仅仅是它们的值......
which may cause problems since:
这可能会导致问题,因为:
String a = new String("lol");
String b = new String("lol");
are two different objects even if they have the same value?
即使它们具有相同的值,它们是两个不同的对象吗?
Whats exactly difference between equals and compareTo implementations in terms of performance and precision?
就性能和精度而言,equals 和 compareTo 实现之间的确切区别是什么?
回答by Jeffrey
Did you try it?
你试了吗?
String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(a.compareTo(b)); // 0
回答by Mesop
First of all ==
compares the references to see if the two objects are the same (so ==
is on the object).
首先==
比较引用以查看两个对象是否相同(对象上也是如此==
)。
Then String.equals()
verify the equality of the content of two strings while String.compareTo()
seek the difference of the content of two strings.
然后String.equals()
在String.compareTo()
求两个字符串内容的差异的同时,验证两个字符串内容的相等性。
So the two following tests are equivalent:
所以下面的两个测试是等价的:
String str = "my string";
if ( str.equals("my second string")) {/*...*/}
if ( str.compareTo("my second string")==0) {/*...*/}
But, since String.equals
is making a reference check first, it's safe when used against null
, while String.compareTo
will throws a NullPointerException
:
但是,由于String.equals
首先进行引用检查,因此在使用时是安全的null
,而String.compareTo
将抛出一个NullPointerException
:
String str = "my string";
if ( str.equals(null)) {/* false */}
if ( str.compareTo(null) {/* NullPointerException */}
回答by Pramod Kumar
String a = new String("lol");
String b = new String("lol");
System.out.println(a == b); // false. It checks references of both sides operands and we have created objects using new operator so references would not be same and result would be false.
System.out.println(a.equals(b)); // true checks Values and values are same
System.out.println(a.compareTo(b)); // checks for less than, greater than or equals. Mainly used in sortings.