Checking a CharSequence for equality – use contentEquals instead of equals, or you will have a bug

In Android, You sometimes get CharSequence as a parameter of a callback.

It might be tempting to check for equality using  “equals” method of a String.

But this would be a bug:

"SomethingSomething".equals(myCharSequence)

because equals requires the other object to be an instance of String as well, as explained in JavaDoc of String.equals :

public boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

The correct way would be to use contentEquals:

"SomethingSomething".contentEquals(myCharSequence)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s