skip to content

What is Java's CharSequence, which types implement it, why would an API accept one rather than a String, and what can that API not assume?

level: middleimportance: should knowfreq 34%

answer

  1. an interface over 16-bit values
  2. String, the builders, one NIO buffer
  3. widest type a reading method needs
  4. equals and hashCode left unrefined
  5. toString before keeping a value

basics

~20 s

CharSequence is the read-only interface over char values, implemented by String, StringBuilder, StringBuffer and CharBuffer, among others. Accepting it spares callers a conversion, but it promises neither immutability nor content-based equals and hashCode, so compare with CharSequence.compare.

solid answer

~40 s

`CharSequence` (since 1.4) is an interface for read-only access to a sequence of `char` values: `length()`, `charAt()`, `subSequence()` and `toString()`, plus defaults such as `chars()`. `String`, `StringBuilder`, `StringBuffer`, `java.nio.CharBuffer` and `javax.swing.text.Segment` implement it. An API such as `Pattern.matcher()` takes it so a caller holding any of these need not convert first, though some JDK methods, like `String.contains()`, still call `toString()` inside. The API cannot assume content-based `equals()` or `hashCode()`: the interface does not refine them and `StringBuilder` keeps `Object`'s identity versions, so compare with `CharSequence.compare()` and avoid arbitrary instances as set elements or map keys. It also cannot assume immutability, so a value it keeps must be copied with `toString()`, nor that `subSequence()` copies, since `CharBuffer` returns a shared view.

code

java · 25 lines
java
import java.nio.CharBuffer;
import java.util.HashSet;
import java.util.Set;

public class CharSequenceEquality {
    public static void main(String[] args) {
        CharSequence text = "abc";
        CharSequence builder = new StringBuilder("abc");
        CharSequence buffer = CharBuffer.wrap("abc");

        System.out.println(text.equals(builder));                     // false: a String equals only a String
        System.out.println(builder.equals(new StringBuilder("abc"))); // false: identity, inherited from Object
        System.out.println(buffer.equals(CharBuffer.wrap("abc")));    // true: remaining chars, buffers only
        System.out.println(buffer.equals(text));                      // false

        System.out.println(CharSequence.compare(text, builder));      // 0
        System.out.println(CharSequence.compare(builder, buffer));    // 0
        System.out.println("abc".contentEquals(buffer));              // true

        Set<CharSequence> seen = new HashSet<>();
        seen.add(text);
        System.out.println(seen.contains(builder));                   // false
        System.out.println(seen.contains(builder.toString()));        // true
    }
}

go deeper

for a junior

Recall that CharSequence is an interface that String, StringBuilder and StringBuffer all implement, offering length, charAt, subSequence and toString. Be able to say that equals between a StringBuilder and a String returns false.

for a middle

Explain the contract: read-only access without immutability, equals and hashCode unrefined, identity on the builders and position-relative methods on CharBuffer. Name CharSequence.compare and contentEquals as the ways to compare content.

for a senior

Show the production judgment: a method that keeps a CharSequence snapshots it with toString, a cache key should not be an arbitrary CharSequence, and a builder shared across threads is the caller's bug that your method inherits.

for a principal

Weigh the API trade-off: a wider parameter type helps callers but commits the method to handling mutable input. Decide per method, preferring String where the value is kept or String's own methods are needed.

## What CharSequence is `java.lang.CharSequence` is an interface, present since Java 1.4, that its Javadoc describes as "a readable sequence of `char` values" giving "uniform, read-only access to many different kinds of `char` sequences". A `char` is a 16-bit value, so `length()` counts those values rather than user-visible characters: an emoji stored as a surrogate pair has length 2. The bugs that follow from that belong with String's internal representation and are not repeated here. The interface is small. In JDK 27, and unchanged from JDK 25, it holds: - **Abstract methods:** `length()`, `charAt(int)`, `subSequence(int, int)` and `toString()`. - **Default methods:** `chars()` and `codePoints()` (since 1.8), `isEmpty()` (since 15) and `getChars(int, int, char[], int)` (since 25). - **A static method:** `CharSequence.compare(CharSequence, CharSequence)` (since 11). `toString()` is redeclared for a reason: the contract says it returns exactly this sequence's characters in the same order, which makes it the portable way to get a `String`. ## Which types implement it The API page lists `String`, `StringBuilder`, `StringBuffer`, `java.nio.CharBuffer` and `javax.swing.text.Segment` as implementing classes, and two subinterfaces, `javax.lang.model.element.Name` and `java.lang.classfile.constantpool.Utf8Entry`. Your own class may implement it too. The four you will meet most do not behave alike: | Type | Content can change? | `equals` and `hashCode` | `subSequence` returns | |---|---|---|---| | `String` | No | By content; equal only to another `String` | A `String`, same as `substring` | | `StringBuilder` | Yes | Identity, inherited from `Object` | A separate `String` | | `StringBuffer` | Yes | Identity, inherited from `Object` | A separate `String` | | `CharBuffer` | Yes; even a read-only buffer shows changes to its source | By remaining chars; equal only to another `CharBuffer` | A `CharBuffer` sharing the content | `CharBuffer` has one more twist: its `CharSequence` methods work relative to its current position. `length()` is `remaining()`, and `charAt(0)` reads the char at `position()`. A relative `get()` writes nothing, yet afterwards `length()`, `charAt(0)` and `toString()` can all report something different. ## Why an API accepts it Accepting the interface lets a caller pass whatever it already holds without converting first. In the JDK, `Pattern.matcher()`, `Appendable.append()`, `Files.writeString()`, `LocalDate.parse()` and `String.join()` all take `CharSequence`. It can also save a copy, when the method reads the characters in place: - `Pattern.matcher(CharSequence)` keeps a reference to the input, and the regex engine reads it through `charAt`. - `Integer.parseInt(CharSequence, int, int, int)` (since 9) parses a range using `charAt`, with no `substring` first. The parameter type promises no such thing, though. `String.contains(CharSequence)` and `String.replace(CharSequence, CharSequence)` call `toString()` on their arguments, and `String.join` converts each element with `String.valueOf`. So the type tells callers what they may pass, not whether a `String` gets built. A workable rule when designing a method: accept `CharSequence` if it only reads the characters during the call. If it keeps the value, or needs `indexOf`, `substring` or other `String` methods, take a `String`, or call `toString()` once on entry. ## What the API cannot assume - **Content equality.** The interface "does not refine the general contracts" of `equals` and `hashCode`, so testing two implementers for equality is "in general, undefined", and the Javadoc calls it inappropriate to use arbitrary instances as set elements or map keys. Each class still obeys `Object`'s general contract; there is simply no promise about content. - **Immutability.** "Read-only" describes what the interface offers, not the object behind it. A `StringBuilder` can change while your method runs or after it returns, and the Javadoc for `chars()` and `codePoints()` says the result is undefined if the sequence is modified during the terminal stream operation. - **Thread safety.** `StringBuilder` instances are documented as not safe for use by multiple threads. - **A snapshot from `subSequence`.** The table shows a separate `String` from the builders and a shared view from `CharBuffer`. - **Ordering.** `CharSequence` does not extend `Comparable`, so `a.compareTo(b)` does not compile on the interface type. - **String's methods.** `indexOf`, `substring`, `split` and the like are not on the interface. - **Cost.** The interface's Javadoc states no cost for `charAt`, so nothing stops an implementation computing each character on demand. ## Comparing and keeping one safely - **Compare content** with `CharSequence.compare(a, b) == 0` (since 11), which orders by `char` values across types; for two instances of one `Comparable` class it defers to that class's `compareTo`, which for `String`, the builders and `CharBuffer` is the same ordering. Or use `someString.contentEquals(cs)` (since 1.5), which synchronizes on the argument when it is a `StringBuffer`. - **Keep a stable value** with `toString()`. The result is a `String`, so it cannot change later and has content-based `equals` and `hashCode`. - **Use a `String` key** in a set or map rather than the raw sequence.

  • How can a method taking a CharSequence compare it with a known constant without relying on the argument's equals()?
    Call `"constant".contentEquals(cs)`, available since 1.5, which is true when the `String` and the argument hold the same `char` values, and synchronizes on the argument if it is a `StringBuffer`. `CharSequence.compare(cs, "constant") == 0`, since 11, gives the same answer. Calling `cs.equals("constant")` is the mistake, because it is false for a `StringBuilder` holding those characters.
  • What does CharBuffer's position do to its CharSequence methods?
    They work relative to it. `length()` equals `remaining()`, `charAt(0)` reads the char at `position()`, and `toString()` returns the characters from the position to the limit. A relative `get()` moves the position, so the same object then reports a shorter length and different characters, with nothing written. Code holding the buffer as a `CharSequence` sees that whenever another part of the program does a relative read.
  • StringBuilder implements Comparable but does not override equals(). What does that mean in practice?
    `StringBuilder` has had `compareTo` since 11, ordering by content, while `equals` stays identity from `Object`. Its natural ordering is therefore inconsistent with equals, and the Javadoc says to take care using one as a key in a `SortedMap` or an element in a `SortedSet`. Those treat a `compareTo` of 0 as the same element, while `equals` would call the two objects different. `StringBuffer` is in the same position.

  • Two CharSequence objects with the same characters are equal, because the interface compares content.
  • CharSequence is read-only, so the object behind it can never change.
  • Any CharSequence works as a HashMap key, just as a String does.
  • subSequence always returns an independent copy of the characters.
  • Accepting CharSequence guarantees that the method never builds a String.
  • length() on a CharSequence counts Unicode characters rather than char values.

CharSequence interface
Java 1.4
CharSequence.compare
Java 11

Assumes Java 27; the CharSequence interface is the same at 25, where getChars, its newest method, first appeared.

context