apache/flink · error · IllegalArgumentException

Length must be between 0 and the current length.

Error message

Length must be between 0 and the current length.

What it means

StringValue is a mutable char-array-backed string. setLength(int len) only truncates: it can shrink the logical length but never grow it, because the backing array is unchanged and the invariant is 0 <= len <= this.len. Any attempt to set a larger (or negative) length throws IllegalArgumentException.

Source

Thrown at flink-core/src/main/java/org/apache/flink/types/StringValue.java:132

     * @param len The length of the substring.
     */
    public StringValue(StringValue value, int offset, int len) {
        this.value = EMPTY_STRING;
        setValue(value, offset, len);
    }

    // --------------------------------------------------------------------------------------------
    //                                Getters and Setters
    // --------------------------------------------------------------------------------------------

    /**
     * Sets a new length for the string.
     *
     * @param len The new length.
     */
    public void setLength(int len) {
        if (len < 0 || len > this.len) {
            throw new IllegalArgumentException("Length must be between 0 and the current length.");
        }
        this.len = len;
    }

    /**
     * Returns this StringValue's internal character data. The array might be larger than the string
     * which is currently stored in the StringValue.
     *
     * @return The character data.
     */
    public char[] getCharArray() {
        return this.value;
    }

    /**
     * Gets this StringValue as a String.
     *
     * @return A String resembling the contents of this StringValue.

View on GitHub (pinned to 2f3c205e92)

Solutions

  1. To truncate only: pass 0 <= len <= current length()
  2. To change content/size arbitrarily, call setValue(...) with the new content instead
  3. Read current bounds with length() before calling setLength

Example fix

// before
sv.setLength(sv.length() + 10); // throws

// after
sv.setValue("new longer content");
Defensive patterns

Strategy: validation

Validate before calling

if (len < 0 || len > sv.length()) {
    throw new IllegalArgumentException("len must be in [0, " + sv.length() + "]");
}
sv.setLength(len);

Prevention

When it happens

Trigger: Calling stringValue.setLength(n) with n negative or n greater than the string's current length(); e.g. trying to pre-size or 'extend' a StringValue the way StringBuilder.setLength does.

Common situations: Developers transferring StringBuilder habits (where setLength can grow) to StringValue; reusing a StringValue and trying to reset it to a capacity rather than a logical length.

Related errors


AI-assisted analysis of apache/flink@2f3c205e92 (2026-08-14). Data as JSON: /api/errors/0879634fdbb0bb4f. Report an issue: GitHub.