What is the difference between the String#equals
method and the String#contentEquals
method?
To find the difference between 2 Strings you can use the StringUtils class and the difference method. It compares the two Strings, and returns the portion where they differ.
In this blog we shall see the difference between string and String. Well technically both of these are the same but with a slight difference. While “string” is a datatype, whereas “String” represents a class. “string” is an alias for System.
Essentially, there is no difference between string and String (capital S) in C#. String (capital S) is a class in the . NET framework in the System namespace.
The String#equals()
not only compares the String's contents, but also checks if the other object is also an instance of a String
. The String#contentEquals()
only compares the contents (the character sequence) and does not check if the other object is also an instance of String
. It can be anything as long as it is an implementation of CharSequence
which covers a.o. String
, StringBuilder
, StringBuffer
, CharBuffer
, etc.
To put it easily: String.contentEquals()
is the smarter brother of String.equals()
, because it can be more free in the implementation than String.equals()
.
There are some reasons why there is a separate String.contentEquals()
method. The most important reason I think is:
equals
method has to be reflexive. That means that: x.equals(y) == y.equals(x)
. This implies that aString.equals(aStringBuffer)
would have to be the same as aStringBuffer.equals(aString)
. This would require the Java API developers to make some special implementation for Strings in the equals()
method of StringBuffer, StringBuilder and CharSequence as well. This would be a mess.This is where String.contentEquals
comes in. This is a standalone method that does not have to follow the strict requirements and rules for Object.equals
. This way, you can implement the sense of "equal content" more freely. This allows you to make intelligent comparisons between a StringBuffer and a String, for example.
And to say what exactly the difference is:
String.contentEquals()
can compare the contents of a String
, a StringBuilder
, a StringBuffer
, a CharSequence
and all derived classes of these. If the parameter is of type String, then String.equals()
get executed.
String.equals()
only compares String objects. All other object types are considered as not equal.
String.contentEquals()
can compare StringBuffer
and StringBuilder
in an intelligent way. It does not call the heavy toString()
method, which copies the whole content to a new String object. Instead, it compares with the underlying char[]
array, which is great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With