CompareTo vs Equals!比较字符串或对象?

时间:2012-05-27 14:07:12

标签: java string compareto string-comparison

快速提问

我正在比较一个字符串,我应该使用equals还是compareTo? 因为我虽然等于区分2个String类型的对象 而不只是他们的价值...

可能导致问题,因为:

String a = new String("lol");
String b = new String("lol");

是两个不同的对象,即使它们具有相同的值?

在性能和精度方面,equals和compareTo实现之间究竟有什么不同?

3 个答案:

答案 0 :(得分:12)

你试过吗?

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

答案 1 :(得分:11)

首先==比较引用以查看两个对象是否相同(因此==在对象上。)

然后String.equals()验证两个字符串内容的相等性,而String.compareTo()寻找两个字符串内容的差异。

因此以下两项测试是等效的:

String str = "my string";

if ( str.equals("my second string")) {/*...*/}
if ( str.compareTo("my second string")==0) {/*...*/}

但是,由于String.equals首先进行参考检查,因此对null使用时是安全的,而String.compareTo会抛出NullPointerException

String str = "my string";

if ( str.equals(null)) {/* false */}
if ( str.compareTo(null) {/* NullPointerException */}

答案 2 :(得分:-2)

    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.
相关问题