The reason for the existence of CharSequence
is that it is often interesting to give more flexibility in the parameters to be accepted by a function. This avoids unnecessary - and often costly - conversions allowing more generic and efficient code.
For example, if your algorithm needs a ensemble of objects, why require that the entry is a ArrayList
? Accepted Collection
, after all ArrayList
implements the interface Collection
(and many other classes as well). Now if he needs a orderly list of elements, it is better to ask as parameter a List
(still giving choice between ArrayList
, LinkedList
and others). And so on...
Java strings are immutable. So if you’re in the middle of a string-handling operation (using StringBuilder
, CharBuffer
or something else of the kind) and need to pass this string to another method, it would be inefficient to first convert into a String
(which implies copying all its contents) and then passing as argument. What the method needs is an "ordered string", so the ideal is to accept any class that implements these requirements.
And about why Java accepts String
in place of CharSequence
, this is answered by @utluiz: why CharSequence
is an interface, which String
implements. Since [in inheritance] it is always possible to use a more specific type in place of a more generic type, a conversion is not necessary.
Excellent, I imagined something like, but I preferred to put doubt and learn the right way.
– hernandev