Thursday, April 4, 2013

The CharSequence Interface


In Java 1.4, both the String and the StringBuffer classes implement the new
java.lang.CharSequence interface, which is a standard interface for querying the length of and
extracting characters and subsequences from a readable sequence of characters. This interface is also implemented by the java.nio.CharBuffer interface, which is part of the New I/O API that was introduced in Java 1.4. CharSequence provides a way to perform simple operations on strings of characters regardless of the underlying implementation of those strings. For example:


/**
 * Return a prefix of the specified CharSequence that starts at the first
* character of the sequence and extends up to (and includes) the first
* occurrence of the character c in the sequence. Returns null if c is
* not found. s may be a String, StringBuffer, or java.nio.CharBuffer.
*/

public static CharSequence prefix(CharSequence s, char c) {
  int numChars = s.length(); // How long is the sequence?
  for(int i = 0; i < numChars; i++) { // Loop through characters in sequence
    if (s.charAt(i) == c) // If we find c,
      return s.subSequence(0,i+1); // then return the prefix subsequence
    }
    return null; // Otherwise, return null
  }

No comments:

Post a Comment