Differences and use of Strings vs. CharSequence

11

Many methods in Java expect parameters CharSequence , but the code runs normally when I pass String without conversion, for example:

String mensagem = intent.getStringExtra(MainActivity.MENSAGEM);

TextView t = (TextView)findViewById(R.id.minha_text_view);

// O Método setText requer o parâmetro do tipo CharSequence, então:
t.setText((CharSequence) mensagem);

// Porem posso usar sem conversão
t.setText(mensagem);

What is the difference between types and why does not an error occur when the unexpected type is passed as a parameter? Is there any downside in not converting String to CharSequence ?

    
asked by anonymous 17.01.2014 / 12:43

2 answers

13

CharSequence is a Java interface that represents a string.

The String class implements this interface and allows you to use polymorphism in methods that receive CharSequence as a parameter, that is, receive a specific implementation, but treat the parameter through a more generic type.

The class String itself uses CharSequence parameters in several methods, for example contains() . This allows interoperability with other text representation classes that also implement the CharSequence interface, such as the StringBuilder .

    
17.01.2014 / 12:50
6

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.

    
17.01.2014 / 13:00