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 for a more generic and efficient code.
For example, if your algorithm needs a set of objects, why would you require the input to be a ArrayList
? Accepts Collection
, after all ArrayList
implements interface Collection
(and many other classes as well). Now, if it needs a ordered list of elements, it's best to ask for a List
(still giving choice between ArrayList
, LinkedList
and others). And so on ...
Java strings are immutable. So if you are in the middle of an operation that handles strings (using StringBuilder
, CharBuffer
or something else) and needs to pass that string to another method, it would be inefficient to convert to String
which implies copying all of its contents) and then pass as an argument. What the method needs is an "ordered sequence of characters," then the ideal is to accept any class that implements these requirements.
And as to why Java accepts String
instead of CharSequence
, this is answered by @utluiz: because CharSequence
is an interface, which String
implements. Since [inheritance] is always possible to use a more specific type instead of a more generic type, a conversion is not necessary.