2

I can see that contentEquals is useful for comparing char sequences but I can't find anywhere specifying which method is the best to use when comparing two strings.

Here mentions the differences between both methods but it doesn't explicitly say what to do with two strings.

I can see one advantage of usng contentEquals is that if the variable passed in has its type changed, a compilation error will be thrown. A disadvantage could be the speed of execution.

Should I always use contentEquals when comparing strings or only use it if there are different objects extending CharSequence?

Simulant
  • 19,190
  • 8
  • 63
  • 98
Michael
  • 3,411
  • 4
  • 25
  • 56

2 Answers2

8

you should use String#equals when comparing the content fo two Strings. Only use contentEquals if one of the Object is not of the type String.

1) it is less confusing. Every Java developer should know what the method is doing, but contentEquals is a more specialised method and therefore less known.

2) It is faster, as you can see in the implementation of contentEquals it calls equals after checking if the sequence is of type AbstractStringBuilder so you save the execution time of that check. But even if the execution would be slower this should not be the first point to make your decision on. First go for readability.

Simulant
  • 19,190
  • 8
  • 63
  • 98
2

The advantage of contentEquals() is support for objects that implement a CharSequence. When you have a StringBuilder it would be wasteful to call StringBuilder.toString() just so you can use equals() a moment later. In this case contentEquals() helps to avoid allocating a new String to do the comparison.

When comparing two String objects just use equals().

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111