tags:

views:

191

answers:

1

Hi,

Why is CharSequence from the Java API an interface? What is the significance of this interface?

+7  A: 

It's just refactored from any existing implementations. One of the benefits is that you can "widen" the input whenever you actually only need one of its methods.

So instead of for example

public void printEveryChar(String string) {
    for (int i = 0; i < string.length(); i++) {
        System.out.println(string.charAt(i));
    }
}

you can have

public void printEveryChar(CharSequence charSequence) {
    for (int i = 0; i < charSequence.length(); i++) {
        System.out.println(charSequence.charAt(i));
    }
}

so that you can pass String, CharBuffer, StringBuilder, StringBuffer and other CharSequence implementations in.

This fact has however nothing to do with java.util.Regex, it only takes benefit of it =)

BalusC
Another place where this abstraction really makes sense is when you use the mutable implementations of CharSequence in I/O, i.e. pass a StringBuilder into a StringWriter without having to create a String first.
Henning
Well in java regexes work on charsequences so it has _something_ to do with regexes. Passing in a custom charsequence can (for example) enable you to detect and interrupt runaway regexes.
Kris