速い質問
文字列を比較していますが、equalsまたはcompareToを使用する必要がありますか?私は等しいので、値だけでなく文字列型の2つのオブジェクトを区別します...
次の理由で問題が発生する可能性があります。
String a = new String("lol");
String b = new String("lol");
同じ値であっても、2つの異なるオブジェクトはありますか?
パフォーマンスと精度の点で、equalsとcompareToの実装の正確な違いは何ですか?
速い質問
文字列を比較していますが、equalsまたはcompareToを使用する必要がありますか?私は等しいので、値だけでなく文字列型の2つのオブジェクトを区別します...
次の理由で問題が発生する可能性があります。
String a = new String("lol");
String b = new String("lol");
同じ値であっても、2つの異なるオブジェクトはありますか?
パフォーマンスと精度の点で、equalsとcompareToの実装の正確な違いは何ですか?
まず==、参照を比較して、2つのオブジェクトが同じであるかどうかを確認します(==オブジェクト上でも同じです)。
次に、2つの文字列の内容の違いを探しString.equals()ながら、2つの文字列の内容が等しいことを確認します。String.compareTo()
したがって、次の2つのテストは同等です。
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 */}
やってみましたか?
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
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.