CharSequence Uniform Read Interface
Accept CharSequence at API boundaries so String, StringBuilder, and StringBuffer all pass through without intermediate toString copies.
Code
public class Redactor {
// 参数收 CharSequence:String、StringBuilder、StringBuffer 都能直接传入
static String maskTail(CharSequence value, int keep) {
if (value.length() <= keep) {
return "*".repeat(value.length());
}
int head = value.length() - keep;
return "*".repeat(head) + value.subSequence(head, value.length());
}
public static void main(String[] args) {
String asString = "sk-live-9f2ab77c01";
StringBuilder asBuilder = new StringBuilder("pk-test-4410ff21aa");
System.out.println("from String: " + maskTail(asString, 4));
System.out.println("from StringBuilder: " + maskTail(asBuilder, 4));
// subSequence 与 String.subSequence 同语义:半开区间 [start, end)
System.out.println("slice: " + asString.subSequence(0, 7));
// chars() 来自 CharSequence 接口本身:任何实现都能转 IntStream
System.out.println("code points: " + asBuilder.chars().count());
}
}The path from top to bottom
CharSequence Uniform Read Interface comes down to the class Redactor and the functions maskTail and main.
What to watch for
- Nothing is pulled from outside the language; the built-in APIs carry the whole example.
Using it
Signature: static String maskTail(CharSequence value, int keep)
The demo output is labeled (from String:, from StringBuilder:, slice:); each label names the call that printed it.
Running the file executes main, which drives maskTail in order.
Key statements
return "*".repeat(head) + value.subSequence(head, value.length());
return "*".repeat(value.length());
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does CharSequence Uniform Read Interface print when run?
- The script runs standalone; its 4 labeled outputs include `from String:`, `from StringBuilder:`, `slice:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.