I can't see any drawbacks in making String.indexOf
part of the interface CharSequence
. The benefit would be that other classes like StringBuffer or StringBuilder would need to implement the indexOf methods too.
So is there any design reason why indexOf
should only be part of String
?
Thank you.
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
There are four variants of indexOf() method.
The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
I am not sure what is the reason for this but I can give an example of class that implements CharSequence
. It is java.nio.CharBuffer
.
Theoretically it could implement indexOf()
by calling charAt()
in loop. But it will not work as user expects. We cannot distinguish between 2 situations: character is not there yet and character is not there and will not be there. In second case indexOf()
should return -1 by contract. In first case it should wait until all bytes arrive. But CharBuffer belongs to non-blocking IO, so it cannot block.
I believe this explains at least one of the possible reasons.
EDIT:
Following very valuable comment by @Pacerier I want to add the following.
IMHO CharSequence
as a very generic interface that is used in different circumstances. The most well known implementors of this interface are String
, StringBuffer
and StringBuilder
that hold the whole content in data structure that allows direct access to any character. This is wrong however in general case. java.nio.CharBuffer
is an example of such case.
I think that's merely an oversight, as indexOf
operation makes sense for any sort of sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With