Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between CharSequence[] and a String[]?

Tags:

java

What is the difference between CharSequence[] and String[]?

like image 376
Brigadier Avatar asked Aug 30 '10 13:08

Brigadier


People also ask

What is difference between CharSequence and String?

A CharSequence is an Interface. String is an immutable sequence of characters and implements the CharSequence interface. CharSequence[] and String[] are just arrays of CharSequence and String respectively.

What is CharSequence in Kotlin?

1.0. interface CharSequence. Represents a readable sequence of Char values.

How do I convert a char to a String?

We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.

Can CharSequence be null?

Because according to you question it can be possible that charSequence will be null too. String. valueOf() doesn't return null. If you want to check charSequence for null, compare it to null, with the == operator.


2 Answers

String implements the CharSequence interface. CharSequence is implemented by String, but also CharBuffer, Segment, StringBuffer, StringBuilder.

So a String[] and a CharSequence[] is essentially the same. But CharSequence is the abstraction, and String is the implementation.

By the way, '[]' denotes an array of objects. So String[] is an array of strings. And String itself is an array of characters.

like image 134
Thierry-Dimitri Roy Avatar answered Oct 17 '22 02:10

Thierry-Dimitri Roy


CharSequence represents an interface to a sequence of characters, with operations common to all classes implementing it. However, in particular, CharSequence does not make any guarantees about whether the sequence is mutable or not. So, you can have an immutable implementing class, like String or mutable ones, like StringBuilder and StringBuffer.

In addition, CharSequence does not refine the general purpose implementations of the equals() or hashCode() methods, so there is no guarantee that objects of different classes implementing CharSequence will compare to be equal even if the underlying sequence that they hold is the same. So, given:

String seq1 = "hello"; StringBuilder seq2 = new StringBuilder("hello"); StringBuffer seq3 = new StringBuffer("hello"); 

comparisons between these three using .equals() return false on Java 1.6, but I can't find any guarantees that this will not change in the future (though it's probably fairly unlikely).

And CharSequence[] and String[] are just arrays of their respective types.

EDIT: The practical upshot of this is to compare CharSequences for equality, you have to use their toString() method and compare the resultant Strings, since this is guaranteed to return true if the underlying sequences are the same.

like image 38
Chinmay Kanchi Avatar answered Oct 17 '22 03:10

Chinmay Kanchi