Вопрос

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.

Это было полезно?

Решение

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.

Java 8 may solve some of these problems. It will allow default implementations on interfaces. e.g.

interface List {
    void sort() default Collections.sort(this);
}

This allow additional methods to be added to interfaces without placing a burden on all implementers to implement that method.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top