Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't method String.indexOf part of interface CharSequence?

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.

like image 359
halex Avatar asked Dec 06 '11 06:12

halex


People also ask

What is a CharSequence in Java?

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.

How do you get the index of the first occurance of character O in string hello how are you?

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.

How many indexOf methods does the string have?

There are four variants of indexOf() method.

What does indexOf return?

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.


2 Answers

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.

like image 85
AlexR Avatar answered Oct 03 '22 04:10

AlexR


I think that's merely an oversight, as indexOf operation makes sense for any sort of sequence.

like image 36
missingfaktor Avatar answered Oct 03 '22 03:10

missingfaktor