Monday, October 21, 2013

CharSequence in Java

As the first blog in the series, I will start with a rather simple concept, CharSequence in Java.

CharSequence is an interface, that is implemented by useful classes that represent an array of characters, such as CharBuffer, Segment, String , StringBuffer and StringBuilder.

An implementation of CharSequence needs to support only 4 methods, charAt(), length(), substring() and toString(). For method that takes a parameter which is a merely a sequence of characters and if the logic of that method doesn't care about the underlying implementation for that sequence of characters, then a CharSequence shall be used. For example, String class has the following method:

public boolean contains (CharSequence s) 

You can pass any object whose class implemented the CharSequence interface. If String is used as the parameter type, then you have to convert the actual parameter to String if it is not already, which might be a waste of CPU time.

Given its convenience, one shall not use CharSequence as key to map or hash table, because the equals() and hashCode() of CharSequence are not refined by the interface. The original equals() and hashCode() of the class that implements CharSequence is likely to fail when comparing against object of another class that implements CharSequence.

Unlike what its name suggests, a char array, i.e. char[], is not a CharSequence for obvious reason (one is an array of primitive type, the other is an object). There are two ways to convert a char[] carray to a CharSequence:

  • CharSequence cs = new String(carray)
  • CharSequence cs = CharBuffer.wrap(carray)